Skip to content
View Knowledge GraphView Article Network
Article Series:iPAS Exam Preparation Notes (1 / 3)

iPAS Exam Preparation Notes - Information Security Engineer

While preparing for the iPAS AI Application Planner (Entry Level) exam recently, I took some practice tests for the Information Security Engineer (Entry Level) exam from last year. Since I passed both, I decided to sign up for both. While using Gemini Gem to drill through practice questions, I found that some terms and details were easily confused, so I had the AI help me organize these notes, which I then supplemented with my past engineering experience.

These are personal notes, and the content is not guaranteed to be strictly within the entry-level scope. I intentionally increased the difficulty in the Gemini Gem prompt settings and raised the difficulty with each round (20 questions per round, 5 rounds total), so I suspect this covers slightly more than the entry level but does not cover the entire intermediate scope.

This is a collection of thoughts as they come, and I may add to them as I continue practicing. Additionally, there are many code snippets and commands in the notes; these are included for better understanding or as a reference when needed, so they are collapsed using details tags.

Basic Concepts

Fundamental Principles and Terminology of Information Security

CIA Triad (Core)

ConceptEnglishDescriptionControl Measures
ConfidentialityConfidentialityEnsuring information is accessed only by authorized partiesEncryption, access control, data classification
IntegrityIntegrityEnsuring information is not modified by unauthorized partiesHash verification, digital signatures, version control
AvailabilityAvailabilityEnsuring authorized users can access information in a timely mannerBackup, disaster recovery, load balancing

Extended Security Attributes

ConceptEnglishDescriptionControl Measures
AuthenticityAuthenticityVerifying the authenticity of the information sourceDigital signatures, PKI, multi-factor authentication
Non-repudiationNon-repudiationEnsuring actions cannot be denied after the factDigital signatures, audit logs, timestamping services
AccountabilityAccountabilityEnsuring actions can be traced to a specific individualIdentity authentication, access logs, separation of duties

AAA Framework (Authentication, Authorization, Accounting)

ElementEnglishDescriptionControl Measures
AuthenticationAuthenticationVerifying user identity ("Who are you?")Account/password, MFA/FIDO2, biometrics
AuthorizationAuthorizationDetermining accessible resources ("What can you do?")RBAC, ABAC, OAuth 2.0
AccountingAccountingRecording user behavior for tracking ("What did you do?")Audit logs, SIEM, NetFlow

CIA vs AAA

  • CIA describes the security attributes that information should possess (protection goals); AAA describes the three stages of access control (implementation mechanisms). They are complementary.

CIA and AAA Relationship Diagram

Diagram

Asset Value Assessment Criteria

Value TypeAssessment FactorsQuantification MethodExample
Direct CostReconstruction, procurement costsMonetary valueSoftware license fees, hardware equipment costs
Indirect CostOperational disruption, reputation lossRevenue loss estimationHourly system downtime loss
Legal CostRegulatory compliance, penalty riskPotential finesGDPR up to 4% of annual turnover
Competitive ValueIntellectual property, trade secretsCompetitive advantage assessmentR&D results, customer lists

Defense in Depth

An architectural strategy of multi-layered security controls, ensuring that even if one layer is breached, other layers still provide protection. The concept is similar to the layered defenses of an ancient castle: if the wall is breached, there is a moat, and further in, there are inner walls and arrow towers. Each layer consumes the attacker's time and increases the risk of exposure.

LayerControl Measures
Governance LayerPolicy, Security Awareness Training
Physical SecurityAccess Control, CCTV
Network PerimeterFirewall / IPS (Intrusion Prevention System) / SDP (Software Defined Perimeter)
Internal NetworkZero Trust / NAC (Network Access Control)
Host SecurityEDR (Endpoint Detection and Response) / AppLocker (Application Whitelisting)
Application SecurityWAF (Web Application Firewall) / RASP (Runtime Application Self-Protection) / SSDLC (Secure Software Development Lifecycle)
Data SecurityEncryption / DLP (Data Loss Prevention)

Security Governance Document Hierarchy

LevelEnglishNatureExample
PolicyPolicyExplains "what" and "why," without specifying technical details. Approved by top management, mandatory; violation constitutes non-compliance."All data transmission must be encrypted"
StandardStandardExplains the "minimum technical threshold to meet policy requirements," mandatory. Specifies versions, algorithms, or settings; violation constitutes non-compliance."Use TLS 1.2 or higher"
ProcedureProcedureExplains "how to execute," listing repeatable operational steps. Mandatory; personnel must follow steps, and deviations require formal approval."Account Application SOP"
GuidelineGuidelineProvides recommended practices, non-mandatory. Personnel can judge whether to adopt based on the situation; deviation does not constitute non-compliance."Recommended password length of 12+ characters"

Governance Document Hierarchy Diagram

Diagram

Information Ethics: PAPA Theory

Proposed by scholar Richard Mason in 1986, it defines four major ethical issues in the information age.

AbbreviationIssueCore Question
P (Privacy)PrivacyIndividuals have the right to decide whether to disclose their own information
A (Accuracy)AccuracyResponsibility for the authenticity and correctness of information
P (Property)Property/OwnershipOwnership of information intellectual property rights
A (Accessibility)AccessibilityEligibility to access information under certain conditions

Difference between Accessibility and Availability

Accessibility ≠ Availability: The former is "who is qualified to use it," while the latter is "whether the system is usable."

Asset Classification and Grading

An asset refers to anything of value to an organization that is worth protecting. It is common to intuitively equate assets with physical hardware, but the scope of assets goes far beyond that; information data itself is often the core value that an organization needs to protect most.

Types of Assets

Based on the role an asset plays in an organization, it can be divided into two categories:

CategoryEnglishDefinitionExamples Covered
Primary AssetPrimary AssetThe core value itself that the organization truly wants to protect; failure to achieve business goals occurs if lostBusiness information and data (customer data, financial statements, trade secrets, intellectual property); business processes and enterprise activities (order processing, customer service, production processes, strategic decisions)
Supporting AssetSupporting AssetResources that carry, process, or support the operation of primary assets; their value is derived from supporting primary assetsHardware (servers, terminals, storage devices); software (OS, applications); network (network equipment, communication lines); personnel (employees, contractors, third parties); physical locations (offices, server rooms); organizational structure and image

Primary assets are the "purpose," and supporting assets are the "means." The key question for judgment is "Why does the organization suffer when this asset is lost?" If the core business value is directly lost, it is a primary asset; if the tools or environment for achieving business are lost, it is a supporting asset.

Classification of Common Items

ItemCategoryReason
InformationPrimaryThe carrier of business value, the object the organization directly wants to protect
Business ProcessPrimaryThe act of creating value for the organization, e.g., order processing
Business ActivitiesPrimarySame scope as business processes, core operations of the organization
HardwareSupportingTools for carrying information and executing processes, replaceable
SoftwareSupportingTools for processing information
NetworkSupportingChannels for transmitting information
PersonnelSupportingRoles that operate systems and execute processes, not the subject of business value itself
SiteSupportingEnvironment housing hardware and personnel
OrganizationSupportingGovernance framework supporting process operation

During risk assessment, first confirm the value of primary assets, then trace the paths through which they are threatened via supporting assets.

Asset Inventory

Asset inventory is the procedure of systematically identifying all assets in an organization and establishing an asset register. The register usually records the asset name, type, location, owner, and value or classification.

Inventory is a prerequisite for subsequent security work because you cannot protect what you don't know exists. Only by taking inventory of what assets the organization holds and who is responsible for each can you classify and grade them, perform risk assessments, and invest protection resources in the most important targets. Inventory is not a one-time task; the register must be updated when assets change.

Two Dimensions of Classification and Grading

After completing the inventory, protection levels must be assigned based on the value of the assets. The determination of the level is based on the impact of the loss of confidentiality, integrity, and availability of the asset, which in practice forms two dimensions:

  • Sensitivity: Focuses on how much damage data leakage would cause; oriented toward confidentiality.
  • Criticality: Focuses on the impact of asset interruption or failure on operations; oriented toward integrity and availability.

Sensitivity Classification of Information

For primary assets like "information," the most common approach is to divide sensitivity levels based on confidentiality, categorized into four levels from low to high based on the severity of damage caused by leakage:

LevelEnglishStandardTypical Example
PublicPublicDisclosure causes no harmMarketing materials on the company website, announced financial reports
InternalInternalDisclosure does not cause major damage, but is not actively leakedInternal company website operational procedure documents
ConfidentialConfidentialDisclosure may damage the enterpriseTrade secrets, unannounced product R&D plans
PrivatePrivateDisclosure may damage the privacy of othersEmployee ID numbers, customer credit card numbers, etc.

Sensitivity Classification Judgment Process

Diagram

Judging Public vs Internal

The damage caused by the leakage of Public and Internal data is not high. Looking only at "whether it causes harm" cannot distinguish between the two. The difference lies in whether the data was originally planned for public disclosure:

  • Public: Data intended for external access, such as marketing brochures or announced financial reports. Classification as Public must be explicitly approved by the asset owner.
  • Internal: Data not planned for public disclosure, such as internal SOPs; even if the impact of leakage is not significant, it does not belong to Public.

Data not approved as Public is defaulted to Internal.

Government Data Classification

Taiwan's government classifies confidential data from high to low according to the "National Secret Protection Act": Absolute Secret → Top Secret → Secret. General official documents are distinguished as "Secret" and "General" according to the "Document Processing Manual." Similar to the four-level enterprise classification logic, the core difference is that government classification focuses on national security impact, while enterprise classification focuses on commercial damage.

Criticality of Assets

Critical Assets refer to assets that are vital to the operation of an organization's core business or mission, and whose loss of confidentiality, integrity, or availability would lead to operational disruption or major damage. The purpose of identifying critical assets is to prioritize limited protection resources for the most important targets.

Sensitivity and criticality are two independent dimensions; the same asset may be highly sensitive but not critical (e.g., archived personal data of resigned employees), or critical but low sensitivity (e.g., a publicly accessible website order service).

Asset Management Roles

After asset classification and grading, it is necessary to clarify who is responsible for deciding the classification and who is responsible for implementing controls.

RoleEnglishTypical HolderResponsibility
Asset OwnerAsset OwnerBusiness Unit ManagerDetermines classification level, approves access authorization, bears ultimate security responsibility
Asset CustodianAsset CustodianIT DepartmentImplements technical measures such as storage, backup, and access control according to the owner's instructions; has no authority to adjust levels independently

Key Points for Asset Classification Judgment

  • Level adjustments (including upgrades and downgrades) must be decided by the asset owner according to organizational policies and risk assessment procedures and cannot be changed arbitrarily; downgrades must be documented in writing for audit purposes.
  • Personally Identifiable Information (ID card, credit card number) → Private; Trade secrets → Confidential.

Differences from Information Security Roles

Similar to the Owner / Custodian direction of asset management, but the legal framework is different and cannot be directly equated:

  • Data Controller vs Asset Owner: The legal responsibility of the controller is defined by GDPR / Personal Data Protection Act, and violations can be penalized by the competent authority; the responsibility of the asset owner comes from internal organizational policies.
  • Data Processor vs Asset Custodian: A written Data Processing Agreement (DPA) is required between the processor and the controller; the relationship between the custodian and the owner is an internal division of duties and does not require external contracting.

Regulations and Compliance

ISO/IEC 27001 and ISMS Basic Requirements

ISO/IEC 27000 Series Standards

StandardTopicCertifiable?Key Description
ISO/IEC 27000Overview of terms and definitions❌ NoDefines terms and concepts used throughout the 27000 series; the base dictionary for reading other standards
ISO/IEC 27001ISMS Requirements✅ YesSpecifies requirements that an organization SHALL establish, implement, and maintain for an ISMS; the core of the series
ISO/IEC 27002Information Security Controls Guidance❌ NoProvides implementation suggestions (SHOULD) for controls in Annex A of 27001; an operational manual, not a specification
ISO/IEC 27003ISMS Implementation Guidance❌ NoExplains how to execute 27001 clauses, providing implementation examples and suggested practices
ISO/IEC 27004Information Security Measurement and Evaluation❌ NoProvides design methods for measurement indicators, corresponding to 27001 Clause 9 (Performance Evaluation), helping organizations evaluate ISMS effectiveness
ISO/IEC 27005Information Security Risk Management❌ NoProvides guidance on risk management processes (Identify → Assess → Treat → Monitor); provides methodology for 27001 risk assessment
ISO/IEC 27006Requirements for Certification Bodies✅ (Applicable to bodies)Specifies conditions that third-party bodies performing ISMS audits and certifications must meet; not applicable to general organizations
ISO/IEC 27007ISMS Audit Guidance❌ NoProvides methodology for performing internal and third-party ISMS audits; supplements ISO 19011 for security audit scenarios
ISO/IEC 27017Cloud Service Security ControlsVariesAdditional control guidance for cloud providers and tenants; supplements 27002 for cloud scenarios
ISO/IEC 27018Public Cloud PII ProtectionVariesGuidance for personal data protection in cloud environments; aligns with the spirit of GDPR
ISO/IEC 27701Privacy Information Management System (PIMS)✅ (Based on 27001)Extends privacy management requirements on top of ISO 27001 / 27002, helping organizations establish PIMS and map to GDPR and other privacy regulations

ISO/IEC 27001 and SoA Key Points

  • 27001 Clauses 4–10 are mandatory (SHALL); organizations must meet all of them to obtain certification.
  • Passing 27001 certification = ISMS management system complies with the standard; 27002 is a reference manual for "suggested practices" and is not itself certifiable.
  • The 93 controls in Annex A are not required to be fully implemented; organizations select applicable items based on risk assessment results and record the reason for selection or exclusion of each control in the Statement of Applicability (SoA).
  • 27002 provides implementation suggestions (SHOULD) for each control; practices can differ from 27002, but this must be explained in the SoA.
  • ISO only publishes standards and does not issue personal qualifications; Lead Auditor certificates are issued by personnel certification bodies (e.g., IRCA, PECB) according to ISO/IEC 17024.

ISO 27001 Annex A Control Categories

TopicEnglishNumber of ControlsScope Covered
OrganizationalOrganizational37Security policy, roles and responsibilities, asset management, supplier relationships, incident management
PeoplePeople8Pre-employment screening, security awareness training, disciplinary procedures, termination procedures
PhysicalPhysical14Secure areas, equipment protection, cabling security, media disposal
TechnologicalTechnological34Access control, encryption, network security, secure development, vulnerability management

11 New Controls in the 2022 Version

The 2022 version has a total of 93 controls (compared to 114 in the 2013 version). During the revision, 11 items were added, and some controls were merged and streamlined. The new items are as follows:

#Control #Control MeasureCategory
15.7Threat IntelligenceOrganizational
25.23Information security for use of cloud servicesOrganizational
35.30ICT readiness for business continuityOrganizational
47.4Physical security monitoringPhysical
58.9Configuration managementTechnological
68.10Information deletionTechnological
78.11Data maskingTechnological
88.12Data leakage preventionTechnological
98.16Monitoring activitiesTechnological
108.23Web filteringTechnological
118.28Secure codingTechnological

ISMS Effectiveness Indicators

Indicator TypeExample IndicatorTarget Value Reference
Prevention EffectSecurity awareness training completion rate, vulnerability patching timeCompletion rate > 95%, high-risk vulnerability patching < 72 hours
Detection CapabilityMean Time to Detect (MTTD), false positive rateMTTD < 24 hours, false positive rate < 5%
Response EfficiencyMean Time to Respond (MTTR), incident resolution rateMTTR < 4 hours, resolution rate > 98%
Compliance LevelAudit finding improvement rate, control effectivenessMajor findings 100% improved, control effectiveness > 90%

ISMS PDCA Cycle

ISMS Core Elements

ElementEnglishDescriptionSpecific Requirements
ContextContextUnderstand organizational environment and stakeholder needsIdentify internal/external issues, regulatory requirements, stakeholder expectations
LeadershipLeadershipCommitment and participation of senior managementEstablish security policy, assign security responsibilities, provide resources
PlanningPlanningRisk assessment and goal settingPerform risk assessment, formulate risk treatment plans, set measurable security goals
SupportSupportProvide necessary resources and capabilitiesManpower allocation, education and training, documented procedures, internal communication
OperationOperationImplement and operate ISMSExecute risk treatment measures, control operation, supplier management
Performance EvaluationPerformance EvaluationMonitor and measureInternal audit, management review, performance indicator monitoring
ImprovementImprovementContinuous improvement mechanismNon-conformity handling, corrective actions, preventive actions

ISO/IEC 27001 adopts the PDCA cycle to ensure continuous ISMS improvement:

StageEnglishCore Task
PlanPlanEstablish ISMS policy, goals, and risk assessment processes; formulate risk treatment plans
DoDoImplement and operate ISMS policies, controls, and procedures
CheckCheckEvaluate ISMS performance, perform internal audits and management reviews, report results to management
ActActTake corrective and preventive actions based on audit results to drive continuous ISMS improvement
Diagram

Audit Types (Three Parties) Comparison Table

TypeEnglishDescriptionTypical Example
1st Party Audit1st PartyInternal audit, organization performs on itselfInternal security audit performed by the company
2nd Party Audit2nd PartyAudit performed on external suppliers or partners; audit by regulatory authorities on subordinate agenciesFinancial Supervisory Commission auditing a bank; customer auditing a supplier
3rd Party Audit3rd PartyPerformed by an independent verification/certification body, can issue certificationISO 27001 certification audit

Judging 2nd Party vs 3rd Party Audits

  • Only 3rd party audits can issue external certification (e.g., passing ISO 27001 certification).
  • Regulatory authority audits (e.g., FSC checking a bank) = 2nd party, not 3rd party.
  • Common misconception: It feels like the regulator is an "external independent third party," but in ISO definitions, external parties with a vested interest (regulators, customers) are all considered 2nd party.

Third-Party Audit Certification Comparison Table

Certification / ReportNatureAudit ScopeCharacteristics
SOC 2 Type 13rd Party Audit ReportWhether system design at a specific point in time meets Trust Services Criteria (TSC)Point-in-time, only proves design is reasonable, does not verify actual operational effectiveness
SOC 2 Type 23rd Party Audit ReportWhether system operation over a period (usually 6–12 months) meets TSCPeriod-of-time, verifies that controls operate effectively over time; more persuasive than Type 1
ISO 27001 Certificate3rd Party CertificationWhether the ISMS management system meets ISO 27001 standardsAnnual surveillance audit + re-certification every three years; focuses on "management system" rather than technical control operational details
PCI DSS AoCAttestation of ComplianceWhether the Cardholder Data Environment (CDE) meets PCI DSS requirementsApplicable to organizations processing credit card transactions; requirements vary significantly by level (Level 1 requires on-site audit by QSA)

SOC 2 Type 1 vs Type 2

  • Type 1 = Blueprint Review: Controls are designed reasonably, but it hasn't been verified if they are actually being executed.
  • Type 2 = Actual Acceptance: During an observation period, controls are verified to be operating effectively.
  • SOC 2 is applicable to all service-oriented organizations that handle customer data, not limited to cloud services. Mainstream cloud service providers (e.g., AWS, Azure, GCP) also produce SOC 2 Type 2 reports for enterprise customers to perform supplier risk assessments.

CSA STAR (Cloud Security Assurance Program)

CSA STAR (Security, Trust, Assurance and Risk) is a cloud service security assurance program launched by the Cloud Security Alliance (CSA), using the Cloud Controls Matrix (CCM) as the assessment benchmark. It currently has two levels:

  • Level 1 Self-Assessment: Cloud providers fill out the CAIQ (Consensus Assessments Initiative Questionnaire) and publish it on the CSA registry; free.
  • Level 2 Third-Party Audit: Verified by an independent audit body; can be combined with ISO/IEC 27001 (STAR Certification) or SOC 2 (STAR Attestation).

NIST CSF and NIST SP 800 Series

NIST CSF (Cybersecurity Framework)

A voluntary cybersecurity framework released by the U.S. NIST (National Institute of Standards and Technology), widely applied across industries. CSF 2.0 (released in 2024) added the "Govern" function, emphasizing the governance level, defining six core functions, and providing a structured method for organizations to assess and improve their security posture.

FunctionEnglishDescriptionCorresponding Activities
GovernGovern (GV)Establish security governance structure and strategy to ensure security risk management aligns with organizational goals (Added in CSF 2.0)Security policy formulation, role and responsibility assignment, supply chain risk management
IdentifyIdentify (ID)Inventory organizational assets, business environment, and risksAsset management, risk assessment, supply chain identification
ProtectProtect (PR)Implement controls to protect critical assetsAccess control, data security, security awareness training, platform security
DetectDetect (DE)Discover security incidents in a timely mannerContinuous monitoring, anomaly analysis, incident detection procedures
RespondRespond (RS)Take action on confirmed incidentsIncident management, analysis, notification, corrective actions
RecoverRecover (RC)Restore affected services to normalRecovery plan execution, improvement measures, external communication
Diagram

NIST CSF vs ISO 27001

  • NIST CSF: Voluntary framework, no certification system, focuses on "what to do" (function-oriented), suitable as a starting point for security maturity assessment.
  • ISO 27001: Can apply for third-party certification, focuses on "how to manage" (management system-oriented), suitable for organizations that need to prove compliance externally.
  • They are complementary: Organizations can use NIST CSF to assess the gap between current status and goals, and then use ISO 27001 to establish a certifiable management system.
  • CSF 2.0 added the "Govern" function, emphasizing that security governance should be led by top management, which is consistent with the management review spirit of ISO 27001.

NIST SP 800 Series

A series of Special Publications released by NIST, covering technical guidance and control specifications for various security topics, primarily used by U.S. federal agencies as a basis for FISMA compliance, but also widely referenced by non-federal organizations.

DocumentTopicKey Description
SP 800-37Risk Management Framework (RMF)Defines a seven-step risk management process (Prepare, Categorize, Select, Implement, Assess, Authorize, Monitor); the main compliance basis for federal agencies
SP 800-53Security and Privacy ControlsHundreds of controls categorized into 20 control families (e.g., AC Access Control, IR Incident Response); the implementation basis for SP 800-37
SP 800-61Incident Handling Guidance(Rev. 3, 2025) Incorporates incident response into the overall risk management context of CSF 2.0; IR activities span all six functions (Govern, Identify, Protect, Detect, Respond, Recover)
SP 800-63Digital Identity GuidelinesSpecifies Authenticator Assurance Levels (AAL), Identity Assurance Levels (IAL), and Federation Assurance Levels (FAL)
SP 800-88Media Sanitization Guidelines(Rev. 2, 2025) Divides media sanitization into three levels: Clear / Purge / Destroy; provides a decision framework for choosing sanitization methods based on data sensitivity and device type
SP 800-171CUI ProtectionSecurity requirements for non-federal systems processing Controlled Unclassified Information (CUI); commonly used for government supply chain compliance
SP 800-207Zero Trust ArchitectureDefines seven Zero Trust basic principles (Tenets) and PE/PA/PEP logical architecture components; provides a reference architecture for federal agencies to migrate to Zero Trust

NIST CSF vs SP 800 Series

  • CSF: Defines "what results to achieve" (high-level function-oriented), suitable for assessing and communicating security posture.
  • SP 800 Series: Defines "what specific controls and processes to implement" (detailed technical-oriented), suitable for federal compliance and detailed implementation planning.
  • They are complementary: CSF is the map, and the SP 800 series is the construction specification for each area.

COBIT Governance Framework

COBIT (Control Objectives for Information and Related Technologies)

An IT governance framework released by ISACA, currently in version COBIT 2019. The core question is "Is IT doing the right things, and doing them compliantly?" The target audience is management and auditors.

COBIT divides IT activities into two levels:

LevelEnglishDescription
GovernanceGovernanceSetting direction, evaluating options, monitoring execution; responsible by the Board or top management
ManagementManagementPlanning, building, executing, monitoring specific activities; responsible by IT management

Common usage scenarios: IT audit, SOX compliance (Sarbanes-Oxley Act), and combined with ISO 27001 as a reference for the governance layer.

ITIL Service Management Framework

ITIL (Information Technology Infrastructure Library)

An IT service management framework released by PeopleCert (formerly AXELOS), currently in version ITIL 4 (2019). The core question is "Is IT service delivered well and operating stably?" The target audience is IT operations and service management teams.

ITIL 4 centers on the Service Value System (SVS), containing 34 management practices, divided into three categories by function:

CategoryDescriptionRepresentative Practices
General Management PracticesManagement activities common across the organizationRisk management, information security management, knowledge management
Service Management PracticesManagement activities specific to IT servicesIncident management, problem management, change control, service desk
Technical Management PracticesTechnology-oriented management activitiesInfrastructure management, deployment management

Intersection with security: Incident Management, Problem Management, and Change Enablement (called Change Control in ITIL v3) processes overlap significantly with security incident handling and vulnerability patching processes.

COBIT vs ITIL

  • COBIT: IT governance framework, answers "is it doing the right things," target is management and auditors.
  • ITIL: IT service management framework, answers "is the service done well," target is the operations team.
  • They are parallel and have no hierarchical relationship. In practice, they can be used together: COBIT sets governance goals, and ITIL implements service processes.

Comparison Table: GDPR vs. Taiwan Personal Data Protection Act (PDPA)

AspectGDPR (EU)Taiwan Personal Data Protection Act (PDPA)
ApplicabilityOrganizations processing personal data of individuals located in the EU (regardless of location; applies to Taiwan enterprises serving EU users)Collection, processing, and use of personal data by public and non-public agencies within Taiwan; extraterritorial application applies to those processing data of ROC citizens abroad (Article 51)
Definition of Personal DataAny information that can directly or indirectly identify a natural personNames, dates of birth, ID numbers, etc., that can directly or indirectly identify an individual
Core PrinciplesLawfulness, fairness, transparency, purpose limitation, data minimization, accuracy, storage limitation, integrity, and confidentialityLegitimate purpose of collection, necessity principle, informed consent (stricter requirements for special categories of personal data, such as written consent)
Data Subject RightsAccess, rectification, erasure (right to be forgotten), portability, objection to processing, restriction of processingQuery, review, copy, supplement, correct, stop collection/processing/use, delete
Data Breach NotificationNotify the supervisory authority (DPA) within 72 hoursNo unified deadline in current law; primarily requires notification to the data subject. The 2025 amendment (Article 12) adds a framework for notifying the competent authority; the effective date is to be determined by the Executive Yuan
Maximum Penalty€20,000,000 or 4% of global annual turnover (whichever is higher)Non-public agencies: Administrative fine of up to NT$ 15 million
Data Protection Officer (DPO)Mandatory in specific circumstancesCurrent law does not adopt the GDPR-style DPO system; the 2025 amendment adds provisions for "Personal Data Protection Officers" in public agencies; effective date TBD
Cross-border TransferMust ensure the recipient country has an adequate level of protection (e.g., SCCs, adequacy decisions)Premised on specific purposes and legal collection/processing/use; the competent authority may restrict international transmission under circumstances listed in Article 21 (e.g., involving major national interests, treaty restrictions, insufficient protection in the recipient country, or circumvention of the Act)

GDPR Applicability and Differences from PDPA

  • Extraterritorial Effect of GDPR: The trigger is not "where the organization is located," but "whether it actively offers goods or services to, or monitors the behavior of, individuals located in the EU" (GDPR Art. 3(2)). Practical indicators include: offering local EU languages, accepting payments in Euros, or explicitly mentioning the EU market in marketing. If a service lacks geographic identification mechanisms and treats all regions equally, it is judged by whether there is an "intent to actively target EU users." It does not automatically apply just because there are EU users.
  • The "Right to be Forgotten" and "Right to Data Portability" are the most significant differences between GDPR and Taiwan's PDPA.
  • GDPR penalties are far higher than those under Taiwan's PDPA; therefore, for enterprises with significant business operations in the EU, GDPR compliance is usually a higher priority.

Taiwan PDPA: Notification Obligations (Articles 8 and 9)

The timing of notification during data collection depends on the method of collection:

Collection MethodArticleTiming of Notification
Direct Collection (Obtained from the data subject, e.g., filling out a form)Article 8At the time of collection
Indirect Collection (Obtained from sources other than the data subject, e.g., from third parties)Article 9Upon the first use of the personal data

The content of the notification is the same for both cases: name of the collecting agency, purpose of collection, categories of personal data, period/region/targets/methods of use, and the rights the data subject may exercise.

Advanced Privacy Concepts

Data Sovereignty: Data is subject to the laws of the country where it is stored. When organizations use cloud services, if data is stored on servers in another country, it may be subject to the laws of multiple jurisdictions simultaneously (e.g., the U.S. CLOUD Act allows the U.S. government to cross-border access data held by U.S. companies).

DPIA (Data Protection Impact Assessment): Article 35 of the GDPR requires prior impact assessments for high-risk personal data processing activities to identify privacy risks and develop mitigation measures. While Taiwan's PDPA lacks explicit DPIA provisions, the competent authority encourages organizations to conduct them voluntarily.

Data Minimization and Purpose Limitation

These are two of the eight core GDPR principles most frequently associated with "data collection":

PrincipleEnglishDefinitionCommon Violation Examples
Data MinimizationData MinimizationCollect only the personal data necessary to achieve a specific purpose; do not collect excessive dataRequiring ID numbers, occupation, or annual income for a basic membership application
Purpose LimitationPurpose LimitationPersonal data can only be used for the purpose stated at the time of collection; it cannot be used for other purposesUsing phone numbers collected for "customer service" for marketing SMS
  • The two are complementary: Purpose Limitation determines "where it can be used," while Data Minimization determines "how much can be collected."
  • Violating Purpose Limitation is generally more serious than violating Data Minimization, as it is difficult for the data subject to remedy the situation once collected data is misused.

Roles in Personal Data Processing

RoleEnglishTypical EntityResponsibilities
Data ControllerData ControllerEnterprise or agency collecting the dataDetermines the purpose and means of processing; bears primary legal liability
Data ProcessorData ProcessorThird-party vendor entrusted with processingExecutes processing according to the Controller's instructions; must sign a Data Processing Agreement (DPA)

HIPAA Medical Data Protection Standards

HIPAA (Health Insurance Portability and Accountability Act)

A 1996 U.S. federal regulation that mandates privacy and security for Protected Health Information (PHI) in the healthcare industry. Applicability is divided into two categories:

  • Covered Entities: Healthcare providers, health insurance companies, and health information exchanges.
  • Business Associates: Third-party vendors entrusted by Covered Entities to process PHI (e.g., cloud storage, billing system providers).
RuleEnglishCore Requirements
Privacy RulePrivacy RuleLimits the scope of PHI use and disclosure; requires patient authorization; grants patients the right to access and amend their own data
Security RuleSecurity RuleMandates administrative (policies/procedures), physical (facility access), and technical (encryption/access control) safeguards for electronic PHI (ePHI)
Breach Notification RuleBreach Notification RuleRequires notification to affected individuals and the HHS within 60 days of an ePHI breach; incidents involving 500+ people require simultaneous notification to local media

💡 Quick Reference: Terminology

  • PHI: Protected Health Information
  • ePHI: Electronic Protected Health Information
  • HHS: Department of Health and Human Services (U.S.)
  • HIPAA vs GDPR: HIPAA applies only to the healthcare industry and is a U.S. regulation; GDPR is cross-industry and applies to all personal data processing within the EU.

Quick Reference: Major Frameworks and Regulations

Framework/RegulationNatureFocusApplicabilityMandatory
ISO 27001Management System StandardInformation Security Management (ISMS)General (all industries)Voluntary (certification available)
NIST CSFSecurity FrameworkCybersecurity Risk Management (6 functions)General (U.S. government priority)Voluntary
NIST SP 800 SeriesTechnical Guidelines/ControlsImplementation details for various security topics (incl. 800-53 controls)U.S. Federal Agencies (others may reference)Mandatory for Federal Agencies
COBITGovernance FrameworkIT Governance and Control ObjectivesIT Governance, AuditVoluntary (often used as audit baseline)
ITILService Management FrameworkIT Service Delivery and OperationsIT Ops/Service Management TeamsVoluntary
GDPRRegulationPersonal Data ProtectionOrganizations processing personal data of individuals in the EUMandatory
Taiwan PDPARegulationPersonal Data ProtectionPublic/non-public agencies in Taiwan; extraterritorial application for processing ROC citizens' dataMandatory
HIPAARegulationMedical Health Information ProtectionU.S. Healthcare IndustryMandatory
PCI DSSIndustry StandardCredit Card Transaction Data SecurityOrganizations processing credit card transactionsMandatory (required by card brands)
  • ISO 27001 vs NIST CSF: 27001 has a third-party certification system; CSF has no certification and focuses on maturity assessment.

Overview of Sub-laws of the Cyber Security Management Act

The Cyber Security Management Act authorizes the establishment of several sub-laws to regulate the implementation details of different aspects:

Sub-lawRegulatory Focus
Enforcement Rules of the Cyber Security Management ActDefinitions and supplementary implementation provisions
Regulations Governing the Classification of Cyber Security Responsibility LevelsAgency responsibility levels (A–E) and required tasks for each level
Regulations Governing Cyber Security Incident Notification, Response, and DrillsIncident notification deadlines, response procedures, and drill items
Regulations Governing Cyber Security Intelligence SharingScope and mechanisms for sharing cyber security intelligence
Regulations Governing Rewards and Punishments for Cyber Security Matters of Public Agency PersonnelProvisions for rewards and punishments for public agency personnel
Regulations Governing Audits of Cyber Security Maintenance Plans for Specific Non-public AgenciesAudit operations for specific non-public agencies

History of Regulation Renaming

The Regulations Governing Cyber Security Incident Notification, Response, and Drills was originally named the Regulations Governing Cyber Security Incident Notification and Response. The Ministry of Digital Affairs amended and released it on January 5, 2026 (Republic of China Year 115), incorporating "drill operations" into the scope of regulation. The old and new names refer to the same sub-law; older documents may still use the old name.

Cyber Security Responsibility Level Operations Requirements (Levels A to E)

Responsibility levels decrease from A to E, with Level A being the most stringent and Level E the most lenient.

Item / Responsibility LevelLevel ALevel BLevel CLevel DLevel E
Dedicated Security Personnel4+2+1+0 (Concurrent role)0 (Concurrent role)
ISMS CertificationFull agency mandatory third-party verificationCore systems must pass third-party verificationCore systems must pass third-party verificationSelf-conducted per competent authoritySelf-conducted per competent authority
SOC MonitoringMust implement, 24/7 monitoring for full agencyMust implement for core systemsOptional based on agency scale/riskNoneNone
Vulnerability ScanningOnce/year (Full agency)Once/year (Core systems)Once/year (Core systems)Once every 2 yearsNone
Penetration TestingOnce every 2 yearsOnce every 2 yearsOnce every 2 yearsNoneNone
Security AuditOnce/yearOnce/yearOnce every 2 yearsNoneNone
Security Training (Hours/Year)Dedicated: 12 hrsDedicated: 12 hrsDedicated: 12 hrsIT concurrent: 3 hrsGeneral concurrent: 3 hrs

Key Distinctions in Responsibility Levels

  • A vs B: The difference in ISMS certification and SOC monitoring lies in scope; Level A covers the entire agency, while Level B targets only core systems.
  • Level C is the Watershed: The minimum threshold for penetration testing and security audits; both are absent from Level D onwards.
  • Concurrent Roles from Level D: No dedicated security personnel; roles are filled by IT staff concurrently, and vulnerability scanning is reduced to once every 2 years.
  • E vs D: Vulnerability scanning remains every 2 years at Level D and is completely canceled at Level E; concurrent personnel roles shift from IT staff to general employees.

Risk Management

Differences Between Vulnerability, Threat, and Risk

TermEnglishExplanationAnalogy
VulnerabilityVulnerabilityA flaw in a system or process that can be exploitedThe door lock is broken
ThreatThreatAn event or actor that could exploit a vulnerability to cause harmA thief is active in the area
RiskRiskThe likelihood and impact of a threat exploiting a vulnerabilityThe probability and loss of being broken into
  • Risk = Threat × Vulnerability × Asset Value. If any factor is zero, the risk does not exist; if any factor is reduced, the overall risk decreases accordingly.
Diagram

Detailed Process for Risk Assessment and Treatment

Diagram
StageInputActivityOutput
Asset IdentificationOrg structure, business processesInventory and classify information assetsAsset register, asset value
Threat/Vulnerability IDAsset register, threat intelligenceIdentify applicable threats and existing vulnerabilitiesThreat list, vulnerability list
Risk AnalysisThreats, vulnerabilities, existing controlsAssess likelihood and impact of riskInherent risk, residual risk
Risk EvaluationRisk value, risk appetiteDetermine risk acceptabilityRisk level, treatment priority
Risk TreatmentUnacceptable risksSelect and implement treatment measuresRisk treatment plan, control measures

Comparison of Risk Analysis Methods

AspectQualitative AnalysisSemi-Quantitative AnalysisQuantitative Analysis
Output FormatLevel description (e.g., High/Med/Low, risk matrix)Relative score (Likelihood score × Impact score)Financial value (e.g., ALE = 120k/year)
Data NeedsExpert judgment, surveys, interviewsExpert judgment + rating scaleHistorical event data, statistical models
DifficultyLowerMediumHigher, requires stats/financial skills
SubjectivityHigh (relies on assessor experience)Medium (mapping still subjective)Low (calculated based on data)
Typical MethodsRisk Matrix, Delphi MethodScore Matrix (High=5, Med=3, Low=1)ALE formula, Monte Carlo, FAIR model
Use CaseInitial screening, quick classificationLack of historical data but need rankingFinancial decision support (e.g., ROSI Analysis)

Combining Qualitative and Quantitative Analysis

In practice, qualitative analysis is often used to quickly screen high-risk items, followed by quantitative analysis on those items to produce financial data. Pure quantitative analysis is rare because it is difficult to obtain reliable historical occurrence rates for many risks.

Risk Matrix

Presents Likelihood and Impact in a 2D matrix; the intersection determines the risk level, assisting in prioritizing treatment. It is a qualitative tool; the output is a level label, not financial value.

Likelihood ↓ / Impact →LowMediumHigh
HighMediumHighHigh
MediumLowMediumHigh
LowLowLowMedium

Delphi Expert Assessment Method

A structured expert consensus method used for risk assessment scenarios lacking historical data where judgment must rely on experts.

  1. Send anonymous questionnaires to experts to collect individual opinions.
  2. Aggregate statistics and provide feedback to all experts.
  3. Experts revise their judgments based on group feedback.
  4. Iterate until opinions converge to a consensus.

The anonymous design aims to eliminate bandwagon effects and authority bias, ensuring independent judgment.

Score Matrix Method

A semi-quantitative analysis tool that maps qualitative levels to organization-defined values and multiplies them to produce a risk priority score. A common example is High=5, Medium=3, Low=1, but values and the number of levels can be adjusted.

Risk Priority = Likelihood Score × Impact Score. Results are for relative ranking only and do not represent actual loss amounts.

Risk Matrix vs Score Matrix

Both have the same structure (Likelihood × Impact); the difference is the output format:

  • Risk Matrix (Qualitative): Outputs level labels (High/Med/Low) for quick classification.
  • Score Matrix (Semi-Quantitative): Outputs numerical scores for cross-item prioritization.

Risk Quantification Formulas

TermChineseExplanation
ALE (Annualized Loss Expectancy)年化損失預期Expected average loss amount within one year, ALE=ARO×SLE
ARO (Annualized Rate of Occurrence)年化發生率Expected number of times a threat event occurs in one year (e.g., 0.1 = once every 10 years)
SLE (Single Loss Expectancy)單次損失預期Expected loss amount per threat event, SLE=AV×EF
AV (Asset Value)資產價值Monetary value of the asset
EF (Exposure Factor)曝險係數Percentage of asset loss if a threat occurs (0–100%)

Formula Chain

ALE=ARO×SLE

SLE=AV×EF

ALE=ARO×AV×EF

Example: Server value 1 million (AV), estimated 60% loss if encrypted by ransomware (EF = 0.6), estimated once every 5 years (ARO = 0.2). → SLE = 1 million × 0.6 = 600k → ALE = 0.2 × 600k = 120k/year

If the annual cost of protective measures is less than 120k, it is cost-effective.

Diagram

Monte Carlo Simulation and ALE

The traditional ALE formula assumes ARO and EF are fixed values, but in reality, these parameters have ranges of uncertainty (e.g., "occurs every 3–7 years"). Monte Carlo simulation uses large-scale random sampling to sample possible values for each variable, running tens of thousands of calculations to produce a probability distribution for ALE rather than a single number. It is the standard method for high-level Quantitative Risk Analysis (QRA).

For example, outputting: "There is a 90% probability that the annualized loss will not exceed 500k" is more valuable for decision-making than "expected loss of 200k."

ROSI (Return on Security Investment)

ROSI measures the financial justification of security controls: How much loss does the investment save?

ROSI=(ALEbeforeALEafter)Annual Control CostAnnual Control Cost×100%
TermExplanation
ALE_beforeAnnualized loss expectancy before implementing controls
ALE_afterAnnualized loss expectancy after implementing controls (after risk reduction)
Annual Control CostTotal cost of ownership for the security measure per year (licensing + labor + maintenance)

Example: Antivirus software annual fee 20k, expected to reduce ALE from 150k to 30k.

  • Saved loss: 150k − 30k = 120k
  • Net benefit: 120k − 20k = 100k
  • ROSI = 100k / 20k × 100% = 500% (save 5 units of loss for every 1 unit invested)

FAIR Model (Factor Analysis of Information Risk)

FAIR is a mainstream quantitative risk analysis framework maintained by The Open Group. It breaks down risk into a quantifiable factor tree structure, ultimately producing a probability distribution of losses.

Diagram
TermExplanation
Loss Event Frequency (LEF)Expected number of times a threat successfully causes loss within a given time
Threat Event Frequency (TEF)Frequency of threat attempts (regardless of success)
VulnerabilityProbability that a threat event converts into a loss event (stronger controls = lower value)
Loss MagnitudeImpact scale of a single loss event, split into Primary Loss and Secondary Loss (e.g., reputation damage, lawsuits)

FAIR vs Traditional ALE

  • The ALE formula is a "point estimate." FAIR uses factor decomposition and probability distributions to conclude "there is an X% probability that loss will not exceed Y amount," providing higher quality decision support.
  • FAIR and ISO 27005/NIST CSF are complementary: ISO 27005 defines the risk management process, while FAIR provides the quantitative analysis method.
  • Adoption barrier: Requires collecting fine-grained threat and control data; suitable for organizations with higher security maturity.

Risk Treatment Strategy Table

Strategy (ISO 27005)EnglishDefinitionExampleUse Case
Risk AvoidanceRisk AvoidanceAbandoning activities or assets that may trigger riskStop using insecure legacy protocols, abandon high-risk marketsRisk is too high and cannot be effectively reduced
Risk ModificationRisk ModificationImplementing controls to reduce likelihood or impactDeploy firewall, implement MFA, encrypt transmissionRisk is within acceptable range, control costs are reasonable
Risk SharingRisk SharingSharing part of the consequences with third parties, usually financial impact or contractual liabilityCyber insurance, outsourcing (MSP/MSSP), SLA compensationHigh impact, but can be dispersed through contracts/insurance
Risk RetentionRisk RetentionAcknowledging risk exists, taking no extra measuresResidual risk is below appetite, remediation cost > potential lossRisk is within tolerable range, or control cost is not cost-effective

ISO 27005 Risk Treatment Process

  1. Risk Assessment: Identification → Analysis → Evaluation.
  2. Based on evaluation, select a treatment strategy (Avoid/Modify/Share/Retain) for each risk.
  3. Develop a Risk Treatment Plan, recording selected strategies and implementation schedules.
  4. Residual Risk must be formally accepted by management.

Risk Terminology Supplementary Table

TermEnglishDefinition
Inherent RiskInherent RiskRaw risk level before any controls, reflecting natural exposure
Residual RiskResidual RiskRisk remaining after treatment, must be formally accepted by management
Secondary RiskSecondary RiskNew risks introduced by the response measures themselves
Risk TransferRisk TransferShifting specific consequences via insurance, contracts, or indemnity clauses
Risk AcceptanceRisk AcceptanceManagement formally accepts risk without further action
Risk CapacityRisk CapacityThe maximum loss limit an organization can bear without jeopardizing survival (objective boundary)
Risk AppetiteRisk AppetiteThe amount of risk an organization strategically chooses to take (subjective willingness, must be ≤ Capacity)
Risk ThresholdRisk ThresholdTrigger level for specific risks, requiring immediate response (usually < Appetite)

Risk Sharing vs Risk Transfer

ComparisonRisk SharingRisk Transfer
ISO 27005 Term✅ Official termCommon colloquialism
DefinitionSharing consequences with third parties (financial, SLA, operational)Shifting consequences via insurance/contracts (emphasizes financial burden)
Substantive DiffOriginal risk and governance responsibility remain with the orgStronger semantics, but in practice usually only shifts financial consequences
ExampleOutsourcing: Service interruption loss shared per SLACyber insurance: Insurer absorbs part of the claim

Terms are often used interchangeably. Regardless of the term, insurance/outsourcing only shifts partial financial consequences; legal obligations under GDPR/PDPA do not disappear.

Risk Retention vs Risk Acceptance

ComparisonRisk RetentionRisk Acceptance
NatureTreatment strategy (one of four)Formal approval action by management
SourceISO 27005 option listISO 27001 Clause 6.1.3e requirement
TimingAfter evaluation, choose no extra controlsAfter any treatment, formal sign-off on residual risk
RelationshipCan stand aloneRequired after every treatment strategy

Both can coexist: Choose "Retention" (no action) → Residual risk = Inherent risk → Management performs "Acceptance" (formal approval).

Hierarchy: Appetite, Capacity, Threshold

  • Risk Capacity: Objective limit; exceeding this means the organization cannot survive.
  • Risk Appetite: Subjective willingness; strategic choice of how much risk to take (≤ Capacity).
  • Risk Threshold: Trigger level for specific risks; requires immediate response (usually < Appetite).

Hierarchy: Capacity ≥ Appetite ≥ Threshold.

Inherent vs Residual Risk

  • No control can reduce risk to zero; residual risk must be formally accepted.
  • Secondary risk is often overlooked: when evaluating response measures, identify if new risks are introduced.

Shadow IT

Definition: Software, cloud services, or hardware used by employees or teams without IT department approval. Shadow IT is like an "underground market" in the office: employees bypass IT procurement to meet deadlines, using personal accounts for SaaS, opening cloud resources, or pasting data into AI assistants. With the spread of SaaS and AI, the scope of Shadow IT has expanded significantly.

Common Types:

TypeExplanationTypical Examples
Shadow SaaSUnauthorized SaaS toolsPersonal Google Drive, Dropbox, Notion
Shadow CloudEngineers opening cloud resources with personal/credit card accountsAWS/Azure accounts bypassing IT
Shadow AIInputting company data into unauthorized AI toolsChatGPT, unvetted AI Coding Assistants
Shadow DataData copied to uncontrolled storageExporting DBs to personal NAS, forwarding emails to personal accounts
Shadow HardwareUnregistered physical devices on corporate networkPersonal NAS, Raspberry Pi, unapproved routers

Common Risks:

RiskExplanation
Data BreachSensitive data enters uncontrolled services; vendor terms may allow training on data
Compliance ViolationStorage location may violate data sovereignty or GDPR
Lack of PatchingSoftware outside corporate processes may have known vulnerabilities
Audit Blind SpotCannot track data flow or usage logs; difficult to trace after incidents
  • Countermeasures: CASB to detect unauthorized cloud services, SaaS management platforms, regular cloud inventory; provide approved alternatives to reduce the incentive to bypass IT.
  • Intersection with BYOD: Employees installing unapproved work apps on personal devices touches both issues.

Incident Management

Information Security Incident Classification

ClassificationEnglishExplanationExamplePriority
Security EventSecurity EventObserved state change in system/networkFirewall log entryLow (Log only)
Security AlertSecurity AlertNotification indicating potential security eventIDS detects abnormal trafficMedium (Analyze)
Security IncidentSecurity IncidentConfirmed violation of policy or threatMalware infection, data breachHigh (Respond)
Major IncidentMajor IncidentSignificant impact on business operationsRansomware locking core systemsHighest (Crisis Mgmt)

Inclusion Relationship

These are nested, not parallel: All incidents are events, but not all events are incidents. Scope converges layer by layer:

text
Event: Any observable state change, including normal logs
└─ Alert: Filtered notifications needing attention, still potentially false positives
   └─ Incident: Confirmed policy violation needing formal response
      └─ Major Incident: Impacting business operations, needing crisis management

Cyber Security Incident Severity Levels (1 to 4)

Higher numbers indicate greater severity.

Item / SeverityLevel 1Level 2Level 3Level 4
Criteria (Core Logic)Non-core system down, no data leakNon-core system paralyzed, or general data leakCore system paralyzed, data tampered, or sensitive data leakNational security threatened, critical infrastructure down
Notification DeadlineWithin 1 hourWithin 1 hourWithin 1 hourWithin 1 hour
Damage Control/RecoveryWithin 72 hoursWithin 72 hoursWithin 36 hoursWithin 36 hours
Report SubmissionWithin 1 monthWithin 1 monthWithin 1 monthWithin 1 month
Typical ExampleWebsite defacement, office PC malwareCore business brief interruption, general data leakMedical record leak, core system crashPower/water grid paralysis, military/diplomatic leak

Taiwan Regulatory Deadline Supplement

Per the current Regulations Governing Cyber Security Incident Notification, Response, and Drills, after completing damage control or recovery, agencies must continue investigation and processing, and submit an investigation, processing, and improvement report within 1 month.

Incident Response (NIST SP 800-61)

NIST SP 800-61 Rev. 3 (April 2025) positions incident response as an integral component of CSF 2.0 risk management, rather than as a standalone "Incident Handling Guide." IR activities span the six Functions of CSF 2.0, with Govern and Identify serving as the governance foundation, Protect responsible for defensive preparation, and Detect, Respond, and Recover handling actual incident management; continuous improvement is embedded throughout the entire IR lifecycle, rather than occurring only post-incident.

Chinese NameCSF 2.0 FunctionCore Task
GovernanceGovernEstablish IR policies, role assignments, authorization, and resource allocation
IdentificationIdentifyIdentify critical assets, assess threat scenarios, and establish IR triggers
ProtectionProtectDeploy detection tools, establish CSIRT, and develop/exercise response plans
DetectionDetectIdentify incidents via SIEM, IDS, and log monitoring; determine severity and scope
ResponseRespondContain affected systems, eradicate malware and vulnerabilities, and execute communication and coordination
RecoveryRecoverRestore systems and verify normal operation, write incident reports, and update response plans

Rev. 2 (2012) Four-Phase Lifecycle

Rev. 2 (withdrawn in April 2025) defined the incident handling lifecycle in four phases:

PhaseChinese NameEnglish NameCore Task
1PreparationPreparationEstablish CSIRT, develop response plans, deploy detection tools, conduct training and exercises
2Detection & AnalysisDetection & AnalysisIdentify incidents via SIEM, IDS, and log monitoring; determine incident severity and scope
3Containment, Eradication & RecoveryContainment, Eradication & RecoveryIsolate affected systems (Containment) → Remove malware and vulnerabilities (Eradication) → Restore systems and verify normal operation (Recovery)
4Post-Incident ActivityPost-Incident ActivityWrite incident reports, review improvement measures, update response plans, preserve evidence (for legal or audit purposes)

💡 Glossary Quick Reference

  • CSIRT: Computer Security Incident Response Team
  • SIEM: Security Information and Event Management
  • IDS: Intrusion Detection System
Diagram

Incident Handling Priorities

  • Containment is the top priority: Isolate infected systems first to prevent the disaster from spreading, then proceed with eradication and recovery.
  • "Lessons Learned" in post-incident activities is the key to continuous improvement; every incident should yield improvement recommendations fed back into the preparation phase.

Differences between CSIRT, CERT, and SOC

OrganizationFull NamePositioningScope of Responsibility
CSIRTComputer Security Incident Response TeamIncident Response TeamInternal organizational security incident detection, analysis, containment, and recovery; can be permanent or ad-hoc
CERTComputer Emergency Response TeamEmergency Response CenterNational or regional level, providing cross-organizational security incident coordination and early warning (e.g., TWCERT/CC)
SOCSecurity Operations CenterSecurity Operations Center24/7 continuous monitoring, handling daily alerts and incident triage; CSIRT handles incidents escalated by the SOC
  • CERTs often serve as national-level coordination centers (e.g., Taiwan's TWCERT/CC, US-CERT), while CSIRTs are typically internal organizational teams.
  • SOCs focus on daily monitoring and initial alert filtering, while CSIRTs focus on in-depth incident investigation and response. Both often work in tandem: SOC detection → escalation to CSIRT for handling.

MTTD / MTTA / MTTR Incident Response Metrics

MetricFull NameDefinitionCalculation
MTTDMean Time To DetectAverage time from when a threat actually occurs to when the organization detects the incidentDetection Time − Incident Occurrence Time
MTTAMean Time To AcknowledgeAverage time from alert trigger to analyst confirmation of handoffHandoff Time − Alert Trigger Time
MTTRMean Time To RespondAverage time from incident detection to completion of response (containment/eradication/recovery)Response Completion Time − Detection Time

Timeline sequence: Threat occurs → MTTD → Detection confirmation/Alert trigger → MTTA → Analyst handoff → MTTR → Resolution

  • Shortening MTTD is more critical than shortening MTTR: The longer an attacker dwells within the organization (Dwell Time), the greater the scope of lateral movement and data exfiltration.
  • Industry Reference: Industry data shows that global average Dwell Time has decreased from hundreds of days to approximately 10 days, but there is still room for improvement.
  • Methods to improve MTTD: SIEM correlation analysis, EDR (Endpoint Detection and Response), and Threat Hunting.
  • Definition in this note: MTTR starts at the detection time, so MTTR encompasses MTTA (MTTA is a sub-interval of MTTR).
  • Another common definition: Some organizations define the MTTR start point as the analyst handoff time; in this case, MTTA and MTTR are non-overlapping, consecutive intervals, and total response time = MTTA + MTTR.
  • Relationship with MTTP: MTTD/MTTA/MTTR are "post-incident" response metrics; vulnerability management has a separate MTTP (Mean Time To Patch), which measures the average time from "vulnerability disclosure to patch completion," falling under the proactive prevention phase KPI.

Post-Incident Report

ElementDescription
Incident TimelineComplete record of every time node from detection, notification, and containment to recovery
Root Cause AnalysisTracing the root cause of the incident, rather than just describing surface symptoms
Impact ScopeAffected systems, number of data records, business downtime
Corrective ActionsRemediation actions taken (e.g., patching vulnerabilities, blocking accounts, updating rules)
Preventive RecommendationsLong-term improvement measures to prevent recurrence of similar incidents

Cross-Platform Log Management and Forensics Path

AspectWindowsLinux
System LogsEvent Viewer: Application, Security, System channels/var/log/syslog (Debian-based) or /var/log/messages (RHEL-based); systemd uses journalctl
Security/Auth LogsSecurity event logs (Login success 4624, Login failure 4625, Account creation 4720)/var/log/auth.log (Debian) or /var/log/secure (RHEL)
Web Server LogsIIS: C:\inetpub\logs\LogFiles\Apache: /var/log/apache2/; Nginx: /var/log/nginx/
Firewall LogsWindows Firewall: Event Viewer Windows Firewall With Advanced Securityiptables: /var/log/kern.log; nftables: journalctl -k
Centralized ManagementWindows Event Forwarding (WEF)rsyslog / syslog-ng remote forwarding to SIEM
Log RetentionGPO configuration for Event Log size and overwrite policylogrotate configuration for rotation and retention days
Critical EventsLogin failure (4625), Permission change (4672), Object access (4663)/var/log/auth.log, auditd rules
Anti-TamperingForward to SIEM and set to read-onlyRemote Syslog + chattr +a (append-only)
Windows / Linux Log Query Command Examples
powershell
# Windows: Query login failure events (4625) from the last day
Get-WinEvent -FilterHashtable @{
  LogName = 'Security'
  Id = 4625
  StartTime = (Get-Date).AddDays(-1)
} -MaxEvents 20

# Windows: Query Security log directly using wevtutil, latest events first
wevtutil qe Security /c:20 /rd:true /f:text
bash
# Linux: View systemd journal for the last hour
sudo journalctl --since "1 hour ago"

# Linux: View logs from the previous boot cycle
sudo journalctl -b -1

# Linux: Set file to append-only to reduce risk of log overwriting
sudo chattr +a /var/log/auth.log
  • Get-WinEvent -FilterHashtable is suitable for precise event filtering based on LogName, Id, and StartTime.
  • wevtutil qe is suitable for quick Event Log queries or exports.
  • journalctl -b -1 is commonly used to compare whether anomalies appeared "before the current boot."
  • chattr +a is a common practice for ext-series file systems, meaning the file can only be appended to, not overwritten or deleted.

Log Management Key Reference Table

AspectKey Description
Log PurposeRecord user activity and anomalous events for post-incident tracking and legal evidence; protect Non-repudiation
Syslog ProtocolDefaults to UDP port 514 (unreliable, packets may be lost during high traffic); switch to TCP for reliable delivery; use TLS (Syslog over TLS) for encrypted transmission
Centralized ManagementImport logs from multiple devices/systems into a SIEM for unified query and analysis
NormalizationLog formats (field names, time formats) vary across devices; must be standardized before centralized analysis
Clock Synchronization (NTP)Device clocks must be synchronized with a standard time source to ensure correct sequencing of cross-device logs, which is the foundation for audit and judicial evidence
Protection and RetentionLogs must not be arbitrarily modified by administrators; retention periods should comply with regulatory or policy requirements

Syslog Severity Levels

LevelValueKeywordDescription
Emergency0EMERGSystem unusable (e.g., kernel panic)
Alert1ALERTAction must be taken immediately (e.g., primary database unresponsive)
Critical2CRITCritical conditions (e.g., hardware failure)
Error3ERRGeneral errors, investigation required
Warning4WARNINGWarning conditions, not errors but noteworthy
Notice5NOTICENormal but significant conditions
Informational6INFOGeneral informational messages
Debug7DEBUGDetailed messages for debugging, usually disabled in production

Common Log Formats

FormatDescription
Syslog (RFC 5424)Linux/Unix standard log protocol, includes Priority, Timestamp, Hostname, App-Name, Message structure
JSONStructured logs, easy for tools like ELK (Elasticsearch + Logstash + Kibana) to parse and query
CEF (Common Event Format)Defined by HP ArcSight, a semi-structured format widely supported by SIEMs, with fixed fields for easy cross-system integration
LEEF (Log Event Extended Format)Structured format used by IBM QRadar, similar to CEF but with slightly different field definitions
W3C Extended Log FormatWeb server log standard, default for IIS

Easily Confused Concepts

  • Log retention protects Non-repudiation, not confidentiality or availability.
  • Syslog runs over UDP, which may lose packets during high traffic; this is a design characteristic of UDP (no retransmission).
  • Different devices have different log formats, requiring Normalization; do not confuse this with De-identification.

Log Management Best Practices

  • Should record: Login success/failure, permission changes, data access, system errors, administrative operations.
  • Should not record: Passwords (including hashes), credit card numbers, PII (ID numbers, medical records), to prevent logs from becoming a source of data leakage.
  • Integrity protection: Logs should be Write Once Read Many (WORM) after transmission to prevent attackers from tampering with logs to cover their tracks.
  • Centralization: Centralize logs to a SIEM or log platform; logs scattered across individual hosts are difficult to correlate and analyze.
  • Retention period: Determined by regulations and policies (e.g., PCI DSS requires at least one year of retention, with the last three months immediately accessible).
  • Alert configuration: Set real-time alerts for high-risk events (multiple login failures, privileged account operations, off-hours access).

Digital Forensics: Order of Volatility

When collecting digital evidence during incident response, evidence should be collected in order from most ephemeral (most volatile) to most stable to prevent permanent data loss after system reboot or power interruption. This principle originates from RFC 3227.

OrderData SourceVolatility
1CPU registers, CPU cacheHighest (disappears when power is cut)
2Main memory (RAM)Extremely high (lost upon shutdown)
3Running processes, network connection states, routing tablesHigh
4Temporary files, Paging File / SwapMedium-High
5Hard drive dataMedium (non-volatile, but may be overwritten by malware)
6Remote logs, SIEM dataLow
7Archival media (tapes, backup discs)Lowest
  • Live Forensics: Capture memory image (Memory Dump) without shutting down, then perform disk imaging (Disk Image).
  • Any operation on the system (e.g., running tools) may alter RAM content; evaluate carefully before evidence collection.
  • Write Blocker: Must avoid any writes to the target media during forensics. Common practices:
    • Hardware Write Blocker: External device that intercepts all write commands at the hardware level; placed between the target disk and the forensic machine; preferred choice.
    • Forensic Boot Environment: Boot from USB into Kali Forensic mode or WinPE forensic environment; local disks are not mounted to avoid OS-induced disk contamination.
    • Image to external media: Use dd, FTK Imager, or dcfldd to read the source and write the image to external media; the original disk is only read.

Disk Imaging Tool Comparison

ToolPlatformFeatures
ddLinux / macOSBuilt-in, bit-for-bit copy, no progress display, no built-in hash, syntax errors may overwrite source
dcflddLinuxForensic-enhanced version of dd (developed by the US DoD Computer Forensics Laboratory), supports on-the-fly hash calculation, progress display, and simultaneous writing to multiple targets
FTK ImagerWindows (GUI)Produced by AccessData, outputs E01 (Expert Witness) or AD1 formats, built-in hash verification, supports preview while copying

Storage Media Space Structure and Hidden Data

After obtaining a disk image, investigators look for hidden or residual data in the following areas in addition to existing files:

AreaDescriptionForensic Significance
Slack SpaceThe OS allocates storage space in fixed-size clusters. If a file size is not an integer multiple of the cluster size, the space between the "actual end of file" and the "end of cluster" is Slack SpaceMay contain residual data (content of the previous file that used the cluster); even if the original file is deleted or overwritten, fragments in Slack Space can still be read
Unallocated SpaceSectors in the file system not occupied by any existing file. After a file is deleted, the OS only marks the cluster as "available" and does not immediately clear the dataData can be recovered by forensic tools (e.g., Autopsy, FTK) before being overwritten by new files; commonly used to find malware or logs deleted by attackers

Windows Execution Trace Forensics (Registry and System Files)

Even if a program has been deleted, the following registry keys retain execution records:

LocationDescription
Shimcache (AppCompatCache)HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\AppCompatCache, records program paths and timestamps executed on the system (updated after reboot)
Amcache.hveC:\Windows\appcompat\Programs\Amcache.hve, records hashes, paths, and first execution times of installed or executed applications
Prefetch (.pf)C:\Windows\Prefetch\, records DLLs loaded when a program is first executed, retains execution count and timestamps of the last 8 executions
MFT (Master File Table)The core metadata table of NTFS, recording attributes (size, timestamp, data location) of every file; even if a file is deleted, MFT records can be read by forensic tools. It records the "current" state of the file and does not retain a history of changes.
$UsnJrnl (Update Sequence Number Journal)Records the sequence of all file and directory change events (creation, deletion, renaming, data changes, encryption, etc.) within a volume, with each record carrying a USN sequence number and timestamp. Even if the target file is deleted, the log record remains, making it the best source for tracking ransomware encryption behavior.
$LogFile (NTFS Transaction Log)Records pending or completed NTFS metadata changes to restore MFT consistency after a system crash. Content is transaction-based and can be used in forensics to restore recent MFT changes, but retention time is short (circular overwrite).
$BitmapRecords the allocation status of each cluster (0 = unused, 1 = allocated). Used in forensics to identify the range of Unallocated Space and confirm which sectors might contain residual deleted data.
  • Forensic value of Shimcache / Amcache: Can prove that an executable once existed on the system and was executed, even if the attacker deleted the file afterward.
  • Prefetch is disabled by default on Windows Server (to improve I/O performance); ransomware often disables Prefetch as an anti-forensics measure.

Common Linux Digital Forensics Paths

/proc/[pid]/ is a virtual directory in Linux procfs that reflects the runtime state of a specific process. Common forensic paths include:

PathContentForensic Use
/proc/[pid]/mapsVirtual memory layout of the process, including mapped file paths and dynamic libraries (.so)Confirm which shared libraries the process loaded; can discover maliciously injected .so files
/proc/[pid]/cmdlineCommand-line arguments used when starting the processView process startup parameters; cannot be read for terminated processes
/proc/[pid]/environEnvironment variables inherited by the processFind hardcoded keys or configuration values
/proc/[pid]/statusProcess status (PID, PPID, UID, GID, etc.)Confirm parent-child relationships and execution identity
/proc/[pid]/fd/All file descriptors currently opened by the processView files or network connections the process is reading/writing
~/.bash_historyShell command history, written upon logoutRestore attacker operation sequence; attackers often clear this with history -c or unset HISTFILE

Chain of Custody

Records the complete history of digital evidence from collection to presentation in court, ensuring evidence integrity and legal validity. Each transfer or access must be recorded:

ItemDescription
WhoIdentity of the person collecting, transferring, or accessing
WhenPrecise timestamp
WhereLocation or storage site
WhatActions performed (e.g., creating a disk image, handing over to forensic personnel)

If the chain of custody is broken (e.g., evidence was left unattended or access was not recorded), the court may not admit the evidence.

Hash Integrity Verification: When collecting evidence, calculate a hash (usually SHA-256) for both the original media and the image immediately, and record it in the chain of custody document. Subsequent forensic work is performed on copies, with hash re-verification before each session. If the hash matches, it proves to the court that the copy is bit-for-bit identical to the original media and has not been tampered with.

PlatformCommand
Linuxsha256sum disk.img
Windowscertutil -hashfile disk.img SHA256
Linux Log Search and Forensic Commands
bash
# Use journalctl to search for SSH events in a specific time range
journalctl --since "2025-01-01 00:00:00" --until "2025-01-02 00:00:00" -u sshd

# Search for SSH brute force (login failure records)
grep "Failed password" /var/log/auth.log | tail -20

# Count source IPs of SSH login failures (sorted by frequency)
grep "Failed password" /var/log/auth.log \
  | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head -10

# Memory Dump — Using LiME kernel module
sudo insmod /opt/lime/lime-$(uname -r).ko "path=/evidence/mem.lime format=lime"

# Use dd to create a bit-for-bit Disk Image
sudo dd if=/dev/sda of=/evidence/disk.img bs=4M status=progress

# Calculate image file hash (ensure evidence integrity, maintain Chain of Custody)
sha256sum /evidence/disk.img > /evidence/disk.img.sha256

Log Recording Security Considerations

  • Prohibit recording sensitive data: Passwords, credit card numbers, personal ID numbers, etc., must not appear in logs.
  • Log integrity protection: Attackers often clear logs after intrusion to cover their tracks; logs should be forwarded in real-time to an independent SIEM or centralized log server.
  • Time synchronization: All systems should synchronize clocks via NTP to ensure the timeline of cross-system logs can be correctly correlated.
  • Log retention period: Set retention policies according to regulatory requirements (e.g., the "Cyber Security Management Act" requires at least 6 months of retention) and business needs.

Memory Forensics

Memory (RAM) is the most volatile source of evidence, containing running processes, network connections, decrypted keys, and malicious code; this information disappears permanently after shutdown. Volatility is the most mainstream open-source memory forensics framework, capable of analyzing memory images (Memory Dump) from Windows / Linux / macOS.

Core Analysis Objectives:

Analysis TargetVolatility Common Commands (v3)Forensic Significance
Running processeswindows.pslist / windows.pstreeList all processes and parent-child relationships, identify malicious programs masquerading as system processes (e.g., fake svchost.exe)
Network connectionswindows.netstatList all TCP/UDP connections and corresponding processes, identify anomalous C2 communication
Injected malicious codewindows.malfindScan memory segments with "Executable + Read/Write (RWX)" protection attributes and no corresponding disk file
DLL listwindows.dlllistList all DLLs loaded by a process, discover abnormally injected DLLs
Registry Hivewindows.hivelistList memory addresses of loaded Registry Hives, can further dump Hives like SAM / SYSTEM

VAD (Virtual Address Descriptor) Tree Structure:

The Windows kernel uses the VAD tree to record the memory segment allocation status and protection attributes (e.g., PAGE_EXECUTE_READWRITE) for each process. During process injection (Process Injection, Process Hollowing), a memory segment with RWX permissions is often allocated first, followed by the injection of Shellcode; at this point, the memory segment exists in the VAD but has no corresponding physical disk file, which is a very obvious anomaly in the VAD tree and the primary detection basis for windows.malfind.

Common Methods for Obtaining Memory Images

Operating SystemToolDescription
WindowsWinPmem, DumpIt, FTK ImagerCommercial or open-source tools that use kernel drivers to read physical memory and output in raw / lime formats
LinuxLiME (Linux Memory Extractor)Kernel module; loaded via insmod to dump memory to local storage or transmit over the network
Virtual MachineHypervisor SnapshotVM snapshots directly include memory state; easiest to obtain and cleanest for forensics

Business Continuity and Disaster Recovery

Backup Type Comparison Table

Backup TypeEnglishBackup ScopeBackup TimeRestore Step CountStorage Space
Full BackupFull BackupAll data, regardless of changes since last backupLongest1 (Full is sufficient)Largest
Differential BackupDifferential BackupAll data changed since the last Full BackupIncreasing (larger over time)2 (Latest Full + Latest Diff)Medium
Incremental BackupIncremental BackupData added or changed since the last any backupShortestMultiple (Latest Full + all subsequent Inc)Smallest

Backup Strategy Trade-offs

  • Full Backup = Slowest backup, simplest restore.
  • Differential Backup = Larger space than incremental, but restore requires only two sets (Full + latest Diff).
  • Incremental Backup = Fastest backup, but restore requires chaining multiple sets, making the process most complex.
  • Common practical strategy: Full on Sunday, Incremental (or Differential) Monday through Saturday.
  • RPO (Recovery Point Objective): The maximum time range of data loss allowed, determined directly by the backup cycle. The higher the backup frequency, the shorter the RPO; Full backup combined with hourly Transaction Logs can compress RPO to within 1 hour.
  • 3-2-1 Backup Rule: At least 3 copies, stored on 2 different media, 1 copy off-site. This is the industry-recognized minimum standard.
  • WORM (Write Once Read Many) Storage: Data cannot be modified or deleted for a specified retention period after being written, effectively resisting ransomware encryption or attacker attempts to delete backups. Cloud services (e.g., Azure Immutable Blob Storage) support WORM mode, which is an important part of modern backup strategies.

SQL Server Backup Mapping (Industry Practice Example):

General Backup TypeSQL Server MappingSQL Server Characteristics
Full BackupFull BackupBacks up the entire database, including data and part of the transaction log; can be restored independently
Differential BackupDifferential BackupBacks up data pages (Data Extent) changed since the last Full; restore requires Full + latest Diff
Incremental BackupTransaction Log BackupBacks up transaction logs since the last log backup; restore requires Full + all subsequent Logs applied in sequence
  • SQL Server's Transaction Log Backup concept is equivalent to incremental backup, but it records "transactions" rather than "changed files."
  • SQL Server also has "Filegroup Backup": Backs up only specific filegroups, suitable for ultra-large databases to avoid full database backups every time.
Diagram

Cross-Platform Backup Tool Comparison

AspectWindowsLinux
Built-in Backup Toolwbadmin (Windows Server Backup), File Historyrsync, tar, cp
Enterprise SolutionSQL Server Backup, Azure BackupBacula, BorgBackup, Restic
SnapshotVSS (Volume Shadow Copy Service)LVM Snapshot, Btrfs/ZFS Snapshot
SchedulingTask Schedulercron / systemd timer
Off-site BackupAzure Blob Storage, AWS S3rsync + SSH, rclone (supports multi-cloud)
Linux Backup Command Examples
bash
# rsync incremental backup (only transfers changed files, suitable for off-site backup)
rsync -avz --delete /var/www/ user@backup-server:/backup/www/

# tar full backup (compresses entire directory into a single file)
tar -czf /backup/full-$(date +%Y%m%d).tar.gz /var/www/

# cron schedule for daily incremental backup at 2 AM
# crontab -e
# 0 2 * * * rsync -avz --delete /var/www/ user@backup-server:/backup/www/ >> /var/log/backup.log 2>&1

# Use find to clean up backup files older than 30 days
find /backup/ -name "full-*.tar.gz" -mtime +30 -delete
Windows Backup Command Examples
powershell
# wbadmin perform full backup to network share
wbadmin start backup -backupTarget:\\BackupServer\Share -include:C: -quiet

# Use robocopy to mirror sync folders (/MIR will delete extra files in destination)
robocopy C:\Data \\BackupServer\Data /MIR /Z /LOG:C:\Logs\backup.log

# Create VSS snapshot (Volume Shadow Copy)
vssadmin create shadow /for=C:

RAID (Redundant Array of Independent Disks) Comparison Table

RAID LevelTechnical PrincipleMin. DisksFault ToleranceRead Perf.Write Perf.Available SpaceUse Case
RAID 0Striping, no redundancy. Data is split and written alternately to disks; all disk space combined into one logical volume20 (Any disk failure results in total data loss)Highest (parallel read)Highest100% (sum of all disks)Video editing scratch space, scenarios requiring high performance without fault tolerance
RAID 1Mirroring, data fully copied to each disk2n-1 (only 1 disk needed)High (dual-track read)No improvement (must write two copies)50%OS disks, scenarios prioritizing data security
RAID 5Striping + Distributed Parity, parity for each stripe is rotated across different disks31 (parity can rebuild one disk)HighDecreased (requires Parity calculation)(n-1)/nNAS (Network Attached Storage), common choice balancing performance and fault tolerance

RAID 5 Parity Distribution Illustration (3 disks)

StripeDisk 0Disk 1Disk 2
1A1A2P(A)
2B1P(B)B2
3P(C)C1C2

P(X) = parity block for that stripe (calculated via XOR). Parity for each stripe is rotated across different disks to avoid a single disk becoming a parity bottleneck. If any disk fails, the missing block can be recalculated using remaining data + parity (e.g., Disk 1 fails → A2 = A1 XOR P(A)).

RAID Common Misconceptions and Practical Configuration

  • RAID is not a backup: RAID only protects against hard drive failure and cannot protect against ransomware encryption, accidental deletion, fire, etc.
  • Common industry combinations:
    • RAID 10 (1+0) = RAID 1 Mirroring + RAID 0 Striping. Balances performance and security; common choice for database servers (e.g., SQL Server recommends RAID 10 for data files).
    • RAID 50 (5+0) = RAID 5 + RAID 0. Commonly used in large storage systems.
  • Enterprise storage usually includes Hot Spare disks for automatic rebuild upon failure.

RAID 5 Intuitive Analogy

Imagine 3 notebooks used to transcribe a story:

  • Notebook A writes paragraph 1, paragraph 2.
  • Notebook B writes paragraph 1, paragraph 3.
  • Notebook C writes paragraph 2, paragraph 3.

Each notebook takes turns being responsible for writing a "summary page" (parity), recording the checksum of the content in the other two. If any one is lost, it can be restored from the content and summary pages of the other two.

  • RAID 6 (Dual Parity): Equivalent to writing two summary pages for each stripe, distributed across two different disks, thus tolerating simultaneous failure of 2 disks. Requires at least 4 disks.
  • RAID 5 writes only one parity, tolerating 1 failure; RAID 6 writes two parities, tolerating 2 failures, but write performance is lower (requires two parity calculations).

Disaster Recovery Site Types Comparison (Hot / Warm / Cold)

TypeEnglishEquipment StatusData RecencyActivation TimeCost
Hot SiteHot SiteFull equipment identical to the primary site, continuously runningReal-time sync (or minimal latency)Within minutes (near-instant switchover)Highest
Warm SiteWarm SiteEquipment ready but on standby, requires manual startup and data syncPeriodic backup (hours to a day)Hours to daysMedium
Cold SiteCold SiteOnly facility, power, and infrastructure, no equipmentRequires restoration from backup mediaDays to weeksLowest

RTO / WRT / MTPD / RPO

  • RTO (Recovery Time Objective): The maximum allowable duration of service interruption after a system failure. Hot Sites have the shortest RTO; Cold Sites have the longest.
  • WRT (Work Recovery Time): The additional time required after the system is back up (RTO achieved) to verify data integrity, adjust configurations, and resume normal operations. The actual interruption time experienced by users = RTO + WRT.
  • MTPD (Maximum Tolerable Period of Disruption): The absolute upper limit of interruption time an organization can withstand. Exceeding this will cause unacceptable business damage. MTPD ≥ RTO + WRT.
  • RPO (Recovery Point Objective): The maximum allowable time range for data loss after a disaster, determined by the backup cycle. The RPO for a Hot Site (real-time sync) is near 0; the RPO for a Cold Site (periodic backup) could be several days old.
  • Risk Appetite drives goal setting: High risk appetite (accepting longer interruptions) → allows for longer RTO/RPO → enables lower-cost recovery solutions.
Diagram
  • RPO looks at the "past" (how much data can be lost), RTO + WRT looks at the "future" (how fast to recover), and MTPD is the hard deadline.
  • Industry Practice: Core systems in the financial industry typically require RTO < 4 hours and RPO < 1 hour, thus mostly adopting Hot Sites + real-time data synchronization (e.g., SQL Server Always On Availability Group).
  • General enterprise ERP systems can accept RTO < 24 hours, where a Warm Site combined with daily differential backups is sufficient.

Data Storage Tiering (Hot / Warm / Cold)

Allocate data to storage tiers with different costs based on access frequency to achieve a balance between performance and cost.

TierCharacteristicsAzure Blob MappingTypical Data
Hot StorageHigh-frequency access, low latency, high storage costHot tierRecent transaction logs, current month reports
Warm StorageLow-frequency access, lower storage cost, retrieval fees applyCool tierHistorical data from the last 1–3 years
Cold StorageArchival use, retrieval takes hours, lowest costArchive tierOld data required for regulatory compliance, archives older than 3 years

Data can be automatically tiered over time (e.g., Azure Blob Lifecycle Management) or moved manually.

Tiered Implementation for Relational Databases

Relational databases (e.g., SQL Server) do not have native tiering management and are usually simulated as follows:

  • Partition + Filegroup: Place recent partitions in SSD filegroups (Hot) and older partitions in HDD filegroups (Cold). Move data as it ages using Partition Switching without row-by-row copying.
  • Archive Database: Batch move data exceeding the retention period to a separate historical database. The primary database remains lean, and the historical database is used for queries only.

Elasticsearch has native ILM (Index Lifecycle Management): Indices can be configured to automatically move from Hot nodes (SSD, for writes and real-time queries) to Warm nodes (HDD, read-only) and then to Cold/Frozen nodes, executed automatically by the engine without manual intervention.

Data Storage Tiering vs. Recovery Sites: Same Name, Different Meaning

"Hot/Warm/Cold" in recovery sites refers to recovery readiness (whether equipment is ready and how fast it can switch); in data storage tiering, it refers to the trade-off between access frequency and cost. The two sets of terms share the same names but represent independent concepts.

BCP Testing Types Comparison

Test TypeEnglishDescriptionRiskCost
Tabletop ExerciseTabletop ExerciseSimulating disaster scenarios via meeting discussions to review plan stepsNone (discussion only)Lowest
Structured Walk-ThroughStructured Walk-ThroughRepresentatives from departments review the plan content together to confirm roles and proceduresNoneLow
Simulation TestSimulation TestSimulating a real disaster scenario (e.g., server room fire), executing notification and response processes, but not actually switching systemsLowMedium
Parallel TestParallel TestRecovery system is actually started and processes business, running alongside the primary system to compare resultsLow (primary system not interrupted)Medium-High
Full Interruption TestFull Interruption TestPrimary system is completely shut down, and all business is switched to the recovery siteHighest (if recovery fails, business is impacted)Highest

Trade-offs and Frequency of BCP Testing

  • Parallel Test: The recovery system actually processes transactions while the primary system remains online, verifying recovery capability without impacting formal business.
  • Full Interruption Test is the only way to verify "true switchover capability," but it carries the highest risk and is usually performed only after management approval.
  • Recommended testing frequency: Tabletop exercises every six months, parallel/interruption tests at least once a year.

Relationship between BCP and DRP

BCP (Business Continuity Plan) covers the complete strategy for maintaining critical business operations during a disaster; DRP (Disaster Recovery Plan) is a subset of BCP, focusing on the technical recovery of IT systems and data. Both are based on the analysis results of the BIA.

Diagram
AspectBCPDRP
ScopeEntire organization (business processes, personnel, communication, IT)IT infrastructure (servers, network, data)
GoalMaintain minimal business operations during a disasterRestore IT systems to normal operating state
Key InputBIA (Business Impact Analysis)RTO/RPO goals from BIA, critical system list, recovery architecture
Responsible RolesSenior management, business ownersIT department, security team

BIA (Business Impact Analysis) is performed before BCP/DRP formulation and serves as the common foundation for both. By analyzing the impact of interruptions to various business processes, it identifies critical business functions and sets RTO, RPO, and recovery priorities, serving as input for BCP strategy planning and DRP technical design.

Physical Security

Physical Security Control Measures Comparison

Control MeasureEnglishDescription
TailgatingTailgatingUnauthorized personnel following authorized personnel through an access point without independent badge verification
PiggybackingPiggybackingAuthorized personnel knowingly and actively bringing in unauthorized personnel (e.g., "holding the door")
MantrapMantrap / AirlockDual-door interlocking design; the second door can only open after the first is closed, forcing individual verification
Surveillance SystemCCTVClosed-circuit television monitoring, providing real-time viewing and post-event review capabilities
Visitor ManagementVisitor ManagementVisitor registration, wearing identification badges, full-time escort, and badge return upon departure
Environmental ControlsEnvironmental ControlsTemperature/humidity monitoring, fire suppression systems (FM-200 gas fire suppression), UPS, backup generators
Cable ManagementCable ManagementNetwork cable labeling and physical isolation to prevent unauthorized connections or eavesdropping

Tailgating vs. Piggybacking

  • Tailgating: The person being followed is unaware; it is a passive security vulnerability.
  • Piggybacking: The person being followed is aware and actively cooperating; it is a violation of security policy.
  • Prevention: A Mantrap can prevent both, as each person must be verified independently.
  • Common server room protection combination: Access card + Mantrap + CCTV + Visitor registration system.

Environmental Controls and Fire Suppression Systems

Control ItemEnglishDescription
HVACHVAC (Heating, Ventilation, and Air Conditioning)Server rooms must maintain 18–27°C and 40–60% relative humidity. Overheating causes equipment failure; high humidity causes condensation that damages circuits.
Wet PipeWet PipePipes are pre-filled with water and spray immediately upon fire detection. Fastest reaction but damages electronic equipment; not suitable for server rooms.
Dry PipeDry PipePipes are filled with compressed air and only inject water when triggered. Suitable for low-temperature environments (anti-freeze), but still sprays water; not suitable for precision equipment areas.
Pre-ActionPre-ActionCombines smoke and temperature detection; water is injected only when both are triggered. Reduces risk of accidental spraying; suitable for data center peripheral areas.
Clean AgentClean AgentUses inert or chemical gases (e.g., FM-200, Novec 1230, CO₂) instead of water. Non-conductive, leaves no residue; first choice for server rooms. CO₂ carries a suffocation risk and must be paired with personnel evacuation alarms.

Fire Suppression System Selection Criteria

  • Office: Wet Pipe, lowest cost, fastest reaction.
  • Server Room Perimeter (Occupied Areas): Pre-Action, dual confirmation reduces accidental spraying.
  • Server Room Core (Server Area): Clean Agent (FM-200 / Novec 1230), does not damage equipment.
  • Unmanned Enclosed Spaces: CO₂, most effective at extinguishing fire but displaces oxygen; personnel must evacuate first.

Electromagnetic Shielding (TEMPEST)

TEMPEST is the electromagnetic leakage protection standard defined by the US NSA (Transient Electromagnetic Pulse Emanation Standard). Electronic equipment generates electromagnetic radiation (Emanation) during operation; attackers can use high-sensitivity receivers at a distance to capture signals and reconstruct screen images or keyboard input.

Protection MeasureDescription
Faraday CageEnclosing a space with conductive materials (metal mesh, metal plates) to block electromagnetic waves. Server room grade requires integration of walls, floors, and ceilings; all incoming/outgoing lines must pass through filters.
TEMPEST Certified EquipmentEquipment designed from the start to reduce electromagnetic radiation, meeting NSA certification standards (e.g., NSTISSAM TEMPEST/1-92).
Distance ControlLimiting the distance between sensitive equipment and building exterior walls (Zone control), utilizing the characteristic that electromagnetic signals attenuate with distance.
White Noise GeneratorEmitting random electromagnetic signals to cover equipment radiation, interfering with the attacker's signal capture.

TEMPEST Protection Focus

  • TEMPEST guards against Passive Eavesdropping; the attacker does not need to touch the target equipment.
  • Daily applications of Faraday cages: Microwave oven shells, mobile signal shielding bags, MRI rooms.
  • Paired with cable management: Fiber optics do not radiate electromagnetic waves and are the preferred transmission medium for high-security environments.

Cable Management Practices

ItemDescription
Structured CablingFollows TIA/EIA-568 standards, distinguishing between Horizontal Cabling and Backbone Cabling.
Labeling SystemUnique identifiers at both ends of every line, corresponding to the Patch Panel Diagram, ensuring traceability.
Physical IsolationPower lines and data lines should be routed in separate conduits to avoid EMI (Electromagnetic Interference). Copper and fiber should be managed separately.
Locked Wiring ClosetWiring Closets / IDF (Intermediate Distribution Frame) should be locked and controlled to prevent unauthorized wiring or eavesdropping.
Fiber Anti-EavesdroppingFiber optics do not radiate electromagnetic waves; eavesdropping requires physical bending of the fiber (Fiber Tapping), which can be detected via optical power meters for abnormal attenuation.

Media Sanitization and Destruction

When devices are retired or replaced, formatting or deleting files does not completely clear data. Choose the appropriate destruction method based on the media type:

MethodHDD (Traditional Magnetic Hard Drive)SSD / Flash Storage
Degaussing✅ Effective (destroys magnetic recording)❌ Ineffective (Flash does not rely on magnetism)
Overwrite / Wipe✅ Effective (still a common Clear method for HDD, but should follow current standards and organizational procedures)⚠️ Partially effective (SSD wear leveling may retain old data blocks; requires vendor-supported secure erase commands)
ATA Secure Erase✅ Effective✅ Effective (if supported by the vendor, the controller ensures complete erasure)
Cryptographic Erase✅ Effective✅ Effective (encrypt all data first, then destroy the key; data becomes unreadable; recommended for SSDs)
Physical Destruction✅ Most thorough✅ Most thorough (NSA requires grinding to ≤ 2mm fragments)

NIST SP 800-88 Rev. 2 "Guidelines for Media Sanitization" (September 2025) divides media sanitization into three levels:

LevelDescriptionApplicable Scenario
ClearLogical sanitization (overwrite), no special equipment requiredGeneral confidential data, redeployment within the organization
PurgeDegaussing, ATA Secure Erase, NVMe Sanitize, or qualified cryptographic erase; resists laboratory-grade recovery attacksSensitive data, device leaving organizational control
DestroyPhysical destruction, ensuring data is completely unrecoverableTop secret level, media must be completely scrapped
  • Conditions for Cryptographic Erase to reach the Purge level: Encryption enabled from device configuration, use of NIST-approved algorithms like AES-256, and verifiable key destruction; if any condition is not met, it only reaches the Clear level.

Common Misconceptions

  • SSDs should not rely on degaussing; prioritize cryptographic erase or physical destruction.
  • "Formatting" ≠ "Sanitization": Formatting only deletes the file index; the data itself remains and can be recovered by forensic tools.

SP 800-88 Rev. 1 (2014) Background

  • Rev. 1 directly listed technical operation details (e.g., "HDD must be overwritten at least once with all zeros"), which has been widely cited for years.
  • Rev. 2 shifts from an "operations manual" to a framework for "establishing an organizational-level Sanitization Program," with most technical details now referencing IEEE 2883, NSA specifications, or organization-approved standards.
  • Rev. 2 adds NVMe-specific guidance and clearly defines the conditions for cryptographic erase to reach the Purge level (resolving the ambiguity in Rev. 1).

Network Security

Four Basic Types of Network Attacks Comparison

Corresponding to the CIA triad, network attacks can be divided into four basic types:

TypeCompromised AttributeDescriptionTypical Methods
InterruptionAvailabilityData is cut off during transmission and cannot reach the destinationDDoS, cutting physical lines
InterceptionConfidentialityIntercepted and eavesdropped during transmission; content leaked but transmission is unaffectedPacket Sniffing, Man-in-the-Middle eavesdropping
ModificationIntegrityData is modified by an unauthorized party before being sent; receiver is unawareMITM packet modification, SQL Injection
FabricationAuthenticityForging identity or data, pretending to be someone elseIP Spoofing, Phishing emails

Security Attributes Corresponding to the Four Attacks

  • Interruption → You don't receive it (Availability destroyed).
  • Interception → You received it, but the content was seen (Confidentiality destroyed).
  • Modification → You received it, but the content was changed (Integrity destroyed).
  • Fabrication → You received it, but the sender is fake (Authenticity destroyed).

Network Architecture and Protocols Comparison

Responsibilities of the OSI 7 Layers

OSI LayerEnglishPDUResponsibilityCommon Protocols & Tech
L7 ApplicationApplicationDataDirectly faces users or applications, provides network service interfaces (e.g., web browsing, file transfer).HTTP/HTTPS, FTP, DNS, DHCP, SSH
L6 PresentationPresentationDataResponsible for data format conversion, encryption/decryption, compression, ensuring different systems understand data formats.SSL/TLS, JPEG, Base64
L5 SessionSessionDataEstablishes, manages, and terminates communication sessions between endpoints, handles connection synchronization and dialog control.NetBIOS, RPC
L4 TransportTransportSegment/DatagramProvides end-to-end (Port to Port) reliable or fast transmission, responsible for flow control and error recovery.TCP (reliable), UDP (low latency)
L3 NetworkNetworkPacketResponsible for cross-network logical addressing (IP address) and routing, determining the best path from source to destination.IP (IPv4/v6), ICMP, BGP, OSPF
L2 Data LinkData LinkFrameResponsible for physical addressing (MAC address) within the same network, frame encapsulation, and error detection, controlling data transmission between nodes.Ethernet (MAC), ARP, VLAN, PPP
L1 PhysicalPhysicalBitDefines electrical, optical, or wireless signal specifications for physical transmission media, responsible for sending/receiving raw bitstreams.1000BASE-T, Wi-Fi RF, Fiber, Coaxial

TCP/IP Model vs. OSI Comparison

The TCP/IP model has two versions: the "Classic 4-Layer" and the "Modern Practical 5-Layer." The early version defined by the US Department of Defense (DoD) is 4 layers (RFC 1122). With the development of network hardware technology, mainstream textbooks and network management certifications (e.g., Cisco CCNA) generally adopt the 5-layer model (also known as the hybrid model).

OSI LayerTCP/IP 4-Layer (Classic DoD)TCP/IP 5-Layer (Modern Practical)
L7 App / L6 Pres / L5 SessApplicationApplication
L4 TransportTransportTransport
L3 NetworkInternetNetwork
L2 Data LinkNetwork AccessData Link
L1 Physical⬆️ (Merged into Network Access)Physical

OSI and TCP/IP Layer Comparison Diagram

Diagram

Practical Understanding of OSI Layering

  • Reason for merging: L5–L7 are merged because modern applications handle connections, encryption, and business logic directly; L1–L2 are merged because physical network cards and drivers usually operate in tandem.
  • PDU and Debugging: Find Port number → Check L4 (Wireshark); Find IP address → Check L3 (Ping, routing table); Find MAC address → Check L2 (Switch, VLAN).
  • TCP Protocol vs. TCP/IP Model: TCP is a single transport protocol at L4; TCP/IP is the collective name for the entire L1–L7 internet communication architecture. Even if UDP is used at the bottom, it still runs within the TCP/IP model framework.
  • For the complete encapsulation/decapsulation process of PDUs at each layer, see the PDU Comparison Table.

💡 Protocol Abbreviation Quick Reference

Protocol Number is located in the L3 IPv4 header, identifying the upper-layer protocol used by the Payload (different from the L4 Port number, which identifies the application).

Protocol NumberProtocolDescription
1ICMPNetwork diagnostics and error reporting (ping uses this protocol)
6TCPReliable transmission, has handshake and retransmission mechanisms
17UDPLow-latency transmission, no connection guarantee
47GREVPN tunnel encapsulation protocol
50ESPIPsec encrypted packet (common in VPNs)
51AHIPsec authentication header, verifies only, no encryption
89OSPFInternal dynamic routing protocol

Other Protocol Abbreviations

AbbreviationFull Name
ARPAddress Resolution Protocol
BGPBorder Gateway Protocol
802.1QVLAN encapsulation standard, adds VLAN Tag to Ethernet frame
PPPPoint-to-Point Protocol
RPCRemote Procedure Call
NetBIOSNetwork Basic Input/Output System

NetBIOS Security Risks

NetBIOS is an extremely old protocol. It is strongly recommended to disable it entirely in modern enterprise networks because:

  • It generates massive broadcast traffic on the internal network, consuming bandwidth.
  • Attackers can use NBT-NS Poisoning to spread laterally within the enterprise network, a common penetration technique for ransomware.
  • Modern Windows file sharing has switched to the more secure SMB (Port 445) and no longer requires NetBIOS.

PDU (Protocol Data Unit) Comparison Table

OSI LayerPDUEnglishDescription
L5-L7 AppDataData / MessageRaw data generated by the application, without any protocol headers.
L4 TransportSegment / DatagramSegment (TCP) / Datagram (UDP)TCP cuts data into segments and numbers them to ensure reliable transmission and order; UDP does not guarantee order or retransmission.
L3 NetworkPacketPacketAdds source/destination IP addresses, determines routing path.
L2 Data LinkFrameFrameAdds source/destination MAC addresses and FCS (Frame Check Sequence) error check code.
L1 PhysicalBitBitElectrical signals, optical signals, or radio waves.

Encapsulation and Decapsulation

Imagine the process of mailing a package: You put the document (Data) into an envelope, write the destination Port (L4), put it into an outer box with the address (L3 + IP), and finally hand it to the courier (L2 converted to frame, L1 converted to electrical signal). Each additional layer is called "Encapsulation"; the receiver opens each layer in order, which is called "Decapsulation."

Encapsulation order: Data → Segment / Datagram → Packet → Frame → Bit

Segment is the packaging unit for TCP; Datagram is for UDP.

TCP and UDP

TCP and UDP are both L4 transport layer protocols that determine "how" data is sent, regardless of "where" it is sent (that is the job of L3 IP).

AspectTCPUDP
Full NameTransmission Control ProtocolUser Datagram Protocol
Connection ModeConnection-oriented (establishes connection before sending)Connectionless (sends directly)
ReliabilityGuaranteed delivery: sequence numbers, ACKs, timeout retransmissionNot guaranteed: packets may be lost or out of order
SpeedSlower (handshake and ACK overhead)Faster (no handshake or ACK)
Common AppsHTTP/HTTPS, SSH, SMTP, FTPDNS queries, VoIP, streaming media, QUIC

TCP Three-way Handshake

TCP must complete three steps before sending data to ensure both sides can send and receive:

Diagram

Common TCP Flags

FlagDescription
SYNRequest to establish connection
ACKAcknowledge receipt
FINRequest to terminate connection normally
RSTForce reset connection (abnormal interruption)
PSHRequest immediate delivery to application layer, don't wait for buffer to fill

Security Relevance

  • SYN Flood: Attacker sends a large number of SYNs but intentionally fails to complete the handshake, exhausting the server's half-open connection table; a DoS attack.
  • TCP RST Injection: Attacker forges RST packets to force-terminate legitimate connections, used to interfere with communication or censorship (firewall blocking often uses this mechanism).
  • UDP Amplification Attack: The connectionless nature of UDP allows attackers to forge source IPs, using services where the response is much larger than the request (e.g., DNS, NTP) to amplify attack traffic. See the L3-L7 Denial of Service chapter.

Common Port Comparison Table

Port numbers are located in the L4 TCP/UDP header and are used to identify which application the packet should be delivered to. For example, when a browser connects to a server, the server uses Port 80 or 443 to receive the request, letting the OS know to hand the traffic to the web service rather than other programs.

Port numbers are divided into three categories by range:

RangeEnglish NameDescription
0–1023Well-Known PortsOfficially assigned by IANA to common services; requires root privileges to bind on Linux/Unix
1024–49151Registered PortsRegistered by third-party applications with IANA, e.g., MySQL (3306), RDP (3389)
49152–65535Ephemeral PortsDynamically assigned by the OS to client temporary connections, released after connection ends

IANA (Internet Assigned Numbers Authority)

Responsible for managing global internet number resources, including IP addresses, AS numbers, and Port number allocation and registration.

Developers usually do not need to apply to IANA for Port numbers; Ports in the Ephemeral range can be used freely. Application is only necessary when developing a protocol or service intended for public release as an industry standard, requiring a fixed Registered Port so other systems can identify which service the Port belongs to.

Common Service Ports

PortProtocolTransportDescription
20FTP-DATATCPFTP data transfer
21FTPTCPFTP control connection
22SSHTCPEncrypted remote login and file transfer (SCP/SFTP)
23TelnetTCPPlaintext remote login, deprecated/insecure
25SMTPTCPEmail transmission (server-to-server)
53DNSTCP/UDPDomain name resolution (UDP for queries, TCP for zone transfers)
67/68DHCPUDP67 for server, 68 for client, dynamic IP allocation
80HTTPTCPPlaintext web transmission
110POP3TCPEmail retrieval (deletes from server after download)
143IMAPTCPEmail retrieval (keeps mail on server)
161/162SNMPUDP161 for queries, 162 for Trap (active alerts)
389LDAPTCPDirectory service query (plaintext)
443HTTPSTCPTLS encrypted web transmission
445SMBTCPWindows file sharing and network neighborhood
465SMTPSTCPSMTP over TLS (encrypted email transmission)
514SyslogUDPSystem log transmission (plaintext, unreliable)
587SMTP SubmissionTCPEmail client submission (requires authentication)
636LDAPSTCPLDAP over TLS (encrypted directory query)
853DoTTCPDNS over TLS (encrypted DNS query)
993IMAPSTCPIMAP over TLS
995POP3STCPPOP3 over TLS
1433MSSQLTCPMicrosoft SQL Server
1521Oracle DBTCPOracle Database
3306MySQLTCPMySQL / MariaDB Database
3389RDPTCPWindows Remote Desktop Protocol
5432PostgreSQLTCPPostgreSQL Database
6379RedisTCPRedis cache database (default no auth, do not expose directly)
8080HTTP AltTCPHTTP alternative Port, common for dev or Proxy
27017MongoDBTCPMongoDB Database

TLS Positioning in OSI Model and HTTPS / HSTS

TLS (Transport Layer Security) spans L5 (Session) and L6 (Presentation) in the OSI model, but is classified as part of the application layer in the TCP/IP model. TLS is not an independent transport protocol; it provides encryption and authentication on top of TCP and below the application layer. Version evolution and security details are in the Encryption Protocol Version Evolution Comparison Table.

HTTPS (HTTP over TLS): HTTP traffic transmitted via TLS encryption, default Port 443.

HSTS (HTTP Strict Transport Security): The server informs the browser via the HTTP header Strict-Transport-Security that subsequent requests to the domain must use HTTPS, preventing SSL Stripping attacks (where an attacker downgrades HTTPS to HTTP).

HSTS DirectiveDescription
max-age=31536000Time (seconds) for the browser to remember this policy; one year in this example.
includeSubDomainsAll subdomains must also use HTTPS.
preloadAdds the domain to the browser's built-in HSTS Preload List, eliminating the HTTP window before the first HSTS connection.

Joining the HSTS Preload List

Standard HSTS requires the user to successfully connect once before the browser remembers "this site requires HTTPS." The first connection before that could still be HTTP, creating a window for attack. The Preload List is a list built into browsers at the factory; once a domain is included, anyone visiting for the first time is forced to use HTTPS.

Application process:

  1. Add the Strict-Transport-Security HTTP response header, which must include preload, includeSubDomains, and a max-age of at least one year.
  2. Submit the domain application at hstspreload.org.
  3. Once approved, it is included in the Chromium source code and subsequently picked up by Chrome, Firefox, Edge, and Safari updates.

Note: includeSubDomains is a mandatory condition; all subdomains must support HTTPS. Once added, removal requires a separate application and waiting for the next browser version update, so ensure the domain can maintain HTTPS long-term before applying.

SSL Stripping Attack

The attacker intercepts the user's first HTTP request, maintains an HTTPS connection to the server, and returns a tampered HTTP page to the victim, causing credentials to be sent in plaintext. See SSL Stripping.

C# Example: HttpClient Configuring TLS 1.3
csharp
using System.Net.Http;
using System.Net.Security;
using System.Security.Authentication;

// Create HttpClientHandler with specific TLS version
SocketsHttpHandler handler = new() {
    SslOptions = new() {
        // Allow only TLS 1.2 and TLS 1.3
        EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13,
    },
};

using HttpClient client = new(handler);

// Send HTTPS request
HttpResponseMessage response = await client.GetAsync("https://example.com/api/data");
response.EnsureSuccessStatusCode();

string body = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Response length: {body.Length} characters");

In practice, manage HttpClient lifecycle via IHttpClientFactory to avoid Socket exhaustion issues.

DNS Security

DNSSEC (DNS Security Extensions) adds digital signatures to DNS responses, ensuring the authenticity and integrity of query results and preventing DNS Spoofing and Cache Poisoning.

Why is DNSSEC needed?

When a browser receives a DNS response saying "The IP of bank.com is 1.2.3.4," how can it confirm that this was not forged by an attacker?

  1. Domain self-signing: bank.com uses a private key to generate RRSIG signatures for all DNS records and publishes the corresponding DNSKEY for verification.
  2. Self-signing is not enough: Anyone can generate their own key pair and sign records; having an RRSIG and DNSKEY is not enough. The resolver also needs to confirm "whether this DNSKEY itself is legitimate."
  3. Upstream credentials (DS records): The .com TLD stores a DS record within its own zone, which contains the hash value of the bank.com DNSKEY. If the resolver finds a match, it means .com acknowledges that this key is authentic.
  4. Tracing further up: Is the .com DNSKEY legitimate? The Root Zone stores the DS record for .com, which is then verified against the root.
  5. The root of trust: The public key of the Root Zone is pre-built into all operating systems and resolvers (Trust Anchor). This is the only link in the entire chain that does not require external verification.

Chain of Trust

Diagram

DNSSEC Record Types

Record TypeFull NameDescription
RRSIGResource Record SignatureDigital signature of a DNS record
DNSKEYDNS KeyStores the zone's public key, used to verify RRSIG
DSDelegation SignerHash of the child zone's public key held by the parent zone, establishing the chain of trust
NSEC / NSEC3Next SecureProves that a specific DNS record does not exist; NSEC3 adds salted hashing to prevent zone enumeration
Windows / Linux DNS Query Command Examples
powershell
# Windows / Linux common: Query basic A and MX records
nslookup example.com
nslookup -type=MX example.com

# Windows: Query A record from a specific DNS Server
Resolve-DnsName -Name example.com -Server 1.1.1.1 -Type A -DnsOnly

# Windows: View the domain's public DNSKEY
Resolve-DnsName -Name example.com -Type DNSKEY -DnsOnly

# Windows: View DNSSEC signature records
Resolve-DnsName -Name example.com -Type RRSIG -DnsOnly
bash
# Linux: Basic query with concise output
dig example.com
dig example.com MX
dig example.com +short

# Linux: Query A record from a specific DNS Server
dig @1.1.1.1 example.com A

# Linux: View the domain's public DNSKEY
dig example.com DNSKEY

# Linux: View the parent zone's DS record
dig com DS
  • Resolve-DnsName allows direct specification of -Server, -Type, and -DnsOnly, making it suitable for basic DNS and DNSSEC troubleshooting on Windows.
  • dig @server name type is the most common basic format; for example, dig @8.8.8.8 example.com MX means "query a specific DNS server for a certain record type."
  • nslookup is suitable for basic queries; Resolve-DnsName and dig provide clearer visibility when observing DNSSEC records or full response fields.

DNSSEC vs. DNS Encryption Protocols Comparison:

ProtocolPurposeDescription
DNSSECIntegrity + AuthenticityVerifies that DNS responses have not been tampered with; queries remain in plaintext
DoH (DNS over HTTPS)Encrypted QueryWraps DNS queries in HTTPS to prevent eavesdropping; Port 443
DoT (DNS over TLS)Encrypted QueryEncrypts DNS queries using TLS; Port 853

Differences between DNSSEC and DoH / DoT

DNSSEC does not encrypt query content: Queries and responses remain in plaintext, ensuring only that the response has not been tampered with. If you need to prevent eavesdropping, you must use DoH or DoT.

VPN (Virtual Private Network) Types and Protocol Comparison

VPN Connection Types and Technical Principles

TypeDescriptionTypical ProtocolUse Case
Site-to-Site VPNConnects two fixed networks via an encrypted tunnel (e.g., HQ ↔ Branch)IPsec (Tunnel Mode)Branch office interconnection, cross-region data centers
Remote Access VPNIndividual users connecting back to the corporate intranet from outsideSSL/TLS VPN, IPsecRemote work, traveling employees accessing internal resources

Technical Differences: Site-to-Site VPN vs. Remote Access VPN

Technical AspectSite-to-Site VPNRemote Access VPN
Connection ArchitectureGateway-to-Gateway: Encrypted tunnels are established by VPN gateway devices at both ends; internal hosts are unawareHost-to-Gateway: User devices establish a direct connection to the corporate VPN server
Tunnel EstablishmentPersistent Tunnel: Once configured, the tunnel exists permanently (Always-On), regardless of data transmissionOn-Demand: Tunnel is established only when the user connects and disappears after disconnection; supports multiple concurrent, independent users
Network TopologyBridge Mode: "Bridges" two local area networks at different locations into one large logical network; devices can communicate directly using internal IPsRoute Mode: Users obtain a virtual IP (usually assigned from an IP Pool by the VPN server); routing tables determine which traffic goes through the VPN
IP Address AssignmentStatic Routing: Subnets at both ends are fixed and non-overlapping (e.g., End A uses 192.168.1.0/24, End B uses 192.168.2.0/24); routing rules are pre-configuredDynamic IP Assignment: Virtual IPs are dynamically assigned from a DHCP Pool; supports IP address reuse
Authentication MechanismDevice Authentication: Based on Pre-Shared Key (PSK), digital certificates, or identity verification between gateways; authenticates devices, not individual usersUser Authentication: Based on username/password, digital certificates, or Multi-Factor Authentication (MFA); each user is authenticated independently
ScalabilityLow Scalability: Depends on the topology chosen for multi-site setupsHigh Scalability: VPN servers can serve thousands of concurrent connections; scalability is achieved by increasing server compute power
Failure ImpactHigh Impact of Single Point of Failure: Gateway failure completely interrupts communication between the two sites, affecting all users at that locationLow Impact of Single Point of Failure: Individual user connection issues do not affect others; server failure can be mitigated with redundancy

Site-to-Site VPN Multi-Site Topologies

Hub-and-SpokeFull Mesh
ArchitectureAll branch sites establish tunnels only with the central HubEvery site establishes a direct tunnel with every other site
Number of ConnectionsN-1N×(N-1)/2
Traffic PathTraffic between branches must route through the HubDirect connection between sites, no detour
Management ComplexityLow, centralized at the HubHigh, connection count grows rapidly as sites increase
LatencyHigher (one extra hop)Lower (direct connection)
Single Point of FailureHub failure interrupts all branch communication; Hubs typically require HA (High Availability)Failure of any site only affects itself; other sites remain connected
Use CaseMany branches, sufficient Hub bandwidthFew sites, latency-sensitive or high traffic volume

VPN Protocol Comparison

ProtocolOperating LayerEncryption MethodCharacteristics
IPsecL3 Network LayerESP (AES + HMAC)Industry standard, suitable for Site-to-Site; supports Transport / Tunnel modes; see IPsec Operation Modes.
SSL/TLS VPNL4-L7TLSAccessible via browser or lightweight client, no dedicated software required; suitable for Remote Access.
WireGuardL3 Network LayerChaCha20 + Poly1305Modern, lightweight protocol with very little code (~4,000 lines); performance superior to IPsec / OpenVPN.

Split Tunneling vs. Full Tunneling

ModeBehaviorProsCons
Full TunnelingAll traffic goes through the VPN tunnelHigh security; all traffic is subject to corporate security policiesHigh bandwidth consumption, impacts performance
Split TunnelingOnly corporate resource traffic goes through VPN; other traffic uses local networkSaves bandwidth, better user experienceLower security; local traffic is not protected

VPN and Zero Trust

  • Traditional VPN Full Tunneling ensures all traffic is inspected, but under a Zero Trust Architecture, every resource has independent access control (PEP), weakening the role of the VPN.
  • Zero Trust does not necessarily eliminate VPNs, but the VPN is no longer the sole trust boundary.

VPN Protocol Details

IPsec IKE Two-Phase Negotiation

PhaseNamePurposeOutput
Phase 1IKE SA EstablishmentNegotiate encryption algorithms, verify identity, establish secure management channelISAKMP SA (Internet Security Association and Key Management Protocol SA)
Phase 2IPsec SA EstablishmentNegotiate encryption parameters for actual data transmission within the Phase 1 secure channelIPsec SA (a pair of unidirectional SAs, each with an SPI identifier)
  • Phase 1 has two modes: Main Mode (6-step exchange, more secure) and Aggressive Mode (3-step exchange, faster but weaker identity protection).
  • Phase 2 uses Quick Mode, which can negotiate multiple IPsec SAs.
  • IKEv2 simplifies the negotiation process, merging Phase 1 + Phase 2 into a 4-message exchange (IKE_SA_INIT + IKE_AUTH).

WireGuard Technical Features

  • Based on the Noise Protocol Framework, using a fixed set of cryptographic primitives (ChaCha20, Poly1305, Curve25519, BLAKE2s), eliminating the need for algorithm negotiation.
  • Uses fixed public key pairing: Each peer is pre-configured with the other's public key, simplifying identity verification.
  • Uses UDP only, no TCP mode.
  • Core code is approximately 4,000 lines (compared to OpenVPN's ~100,000 lines), making it easy to audit for security.
  • Connection establishment time is typically under 100ms (IPsec / OpenVPN usually take several seconds).

SSL/TLS VPN Modes

ModeDescriptionUse Case
ClientlessAccess Web applications via browser, no software installation requiredTemporary access, partners, BYOD devices
Full-tunnel ClientInstall dedicated client, all traffic transmitted via TLS tunnelRemote employees requiring full network access
  • Clientless mode only supports Web applications and some protocols (e.g., RDP over HTML5); functionality is limited but deployment is easiest.
  • Full-tunnel Client provides functionality comparable to IPsec VPNs but has stronger firewall traversal capabilities via TLS (using TCP Port 443).

IPsec Operation Modes

AspectTransport ModeTunnel Mode
Encryption ScopeEncrypts Payload only (IP header not encrypted)Encrypts the entire original IP packet (including header), then wraps it in a new IP header
IP Header VisibilityOriginal IP header is preserved, revealing real source and destination IPsOriginal IP header is encrypted and hidden; outer header shows VPN gateway IP
Typical UseHost-to-Host communicationGateway-to-Gateway (Site-to-Site VPN) or Remote Access VPN
SecurityLower (attacker can see communicating IPs)Higher (original IP hidden, only VPN gateway address visible)
Packet Structure[Original IP Header][IPsec Header][Encrypted Payload][New IP Header][IPsec Header][Encrypted (Original IP Header + Payload)]
Diagram

Differences between IPsec AH and ESP

  • AH (Authentication Header): Provides integrity verification and source authentication only; does not provide encryption.
  • ESP (Encapsulating Security Payload): Provides encryption + integrity verification + source authentication.
  • In practice, most VPNs use ESP + Tunnel Mode.
  • Transport mode is commonly used for secure communication between two hosts within the same local area network.

QUIC Protocol and HTTP/3

QUIC is a transport layer protocol developed by Google and standardized by the IETF (RFC 9000). HTTP/3 uses QUIC as its foundation, replacing the TCP + TLS architecture of HTTP/2.

Comparison AspectHTTP/2 (TCP + TLS)HTTP/3 (QUIC)
Transport LayerTCPUDP (QUIC implements reliable transport over UDP)
EncryptionTLS (layered, independent handshake)Built-in encryption (QUIC handshake merged with TLS 1.3)
Connection Establishment3-way TCP + TLS handshake (1–2 RTT)0-RTT or 1-RTT (0-RTT resumption for known servers)
Head-of-Line (HOL) BlockingExists at TCP layer (one lost packet stalls all streams)None (streams are independent; single packet loss does not affect others)
Connection MigrationIP change requires connection rebuildUses Connection ID; maintains connection when changing IP/network (e.g., Wi-Fi to mobile)
Firewall/NAT TraversalTCP 443 widely allowedUDP 443, may be blocked in some environments

Security Considerations:

  • QUIC mandates TLS 1.3, preventing downgrade to weaker encryption versions, offering better security than the negotiable TLS 1.2.
  • Because it uses UDP, traditional stateful TCP firewalls may not be able to perform deep inspection of QUIC traffic, posing visibility challenges for enterprises.
  • 0-RTT data may be subject to Replay Attacks; servers must implement idempotency protection for 0-RTT requests.

Key Transport Performance Terms

  • RTT (Round-Trip Time): The time it takes for a packet to be sent and a response to be received. Higher RTT means higher latency. Establishing a connection requires several round trips, each consuming RTT time.
  • TCP 3-way Handshake: TCP must complete three steps (SYN → SYN-ACK → ACK) before data transmission, consuming 1 RTT. HTTPS adds a TLS handshake on top, totaling 2 RTTs before data transmission begins.
  • HOL Blocking (Head-of-Line Blocking): TCP requires packets to arrive in order; one lost packet forces all subsequent packets to wait for retransmission, stalling even unrelated data streams.
  • Jitter (Transmission Delay Variation): Inconsistency in packet arrival times. RTT is "average latency," while Jitter is the "fluctuation amplitude of latency." Real-time communications like VoIP and video conferencing are extremely sensitive to Jitter; high Jitter causes choppy audio or frozen video. Attackers can intentionally create high Jitter via network congestion (e.g., DDoS) to degrade service quality or trigger timeouts.

NAC and 802.1X Authentication

NAC (Network Access Control) is a mechanism that performs two types of checks before a device is allowed onto the network:

  • Authentication: Verifies whether the device or user has permission to access the network, typically implemented via 802.1X.
  • Posture Assessment: Verifies whether endpoint security settings comply with policy, including OS patches, antivirus status, presence of prohibited software (e.g., P2P tools), and personal firewall status.

Devices failing any check are isolated to a restricted VLAN, allowed only to access remediation servers, or denied connection entirely.

NAC Architecture:

Diagram

802.1X handles the "Authentication" aspect. It is an IEEE standard for Port-based Network Access Control, using EAP (Extensible Authentication Protocol) as the authentication framework.

802.1X Three Roles:

RoleDescriptionCommon Implementation
SupplicantDevice or software requesting network accessWindows built-in 802.1X Client, wpa_supplicant (Linux)
AuthenticatorNetwork device controlling port accessEnterprise switches, wireless APs
Authentication ServerVerifies identity and determines authorizationRADIUS server (e.g., FreeRADIUS, Microsoft NPS)

802.1X Authentication Flow:

Diagram

Comparison of Common EAP Methods:

EAP is just a framework; actual authentication strength depends on the chosen EAP method. The core difference lies in "which side requires a certificate" and "whether a TLS tunnel is established."

EAP MethodServer CertClient CertAuth TypeCharacteristics
EAP-MD5Unidirectional (Server cannot be verified)Weakest; vulnerable to Man-in-the-Middle attacks, not recommended.
PEAPUnidirectional (Verify Server)Establishes TLS tunnel first; client authenticates via password (MSCHAPv2) inside the tunnel; most common in Windows enterprise environments.
EAP-TTLSUnidirectional (Verify Server)Similar to PEAP, but supports more inner protocols (PAP, CHAP, MSCHAPv2, etc.); better cross-platform compatibility.
EAP-TLSBidirectional (Mutual Auth)Both sides require PKI certificates; highest security, but highest deployment cost (requires client certificate management).
EAP-FASTOptionalUnidirectional (Default)Proposed by Cisco; replaces certificates with PAC (Protected Access Credential) to avoid certificate management burden.

Private IP and CIDR Subnetting

Private IP Ranges (RFC 1918)

Private IPs are routed only within an organization; external communication requires NAT to translate to a public IP. Public IPs are assigned by IANA/ISP and are globally unique; private IPs are managed by the organization and can be reused across different organizations.

Private RangeCIDRAvailable HostsCommon Scenario
10.0.0.0 – 10.255.255.25510.0.0.0/816,777,214Large enterprise intranet
172.16.0.0 – 172.31.255.255172.16.0.0/121,048,574Medium enterprise
192.168.0.0 – 192.168.255.255192.168.0.0/1665,534Home/Small office

CIDR Subnetting

In a CIDR prefix (/n), the first n bits are the network portion, and the remaining (32 - n) bits are the host portion.

Available hosts = 2^(32-n) - 2 (excluding network address and broadcast address)

CIDRHost BitsAvailable HostsUse Case
/22101,022Large department (~1,000 devices)
/248254General office subnet
/26662Small department
/28414Small isolated subnet
/3022Point-to-Point connection

Security Significance of Subnetting

Shrinking subnets reduces the "Blast Radius": if one segment is compromised, the impact is limited to hosts within that subnet.

Practical example: Finance department of 10 people → /28 (14 available IPs), preventing other departments in the same building from connecting directly.

Network Segmentation

Network segmentation divides a large network into multiple smaller security zones, limiting Lateral Movement. Even if an attacker compromises one segment, they cannot directly access resources in other segments.

ImplementationDescription
VLANCreates logically isolated Broadcast Domains on the same physical switch. Communication between VLANs must pass through an L3 router or firewall.
ACLSets rules on routers or L3 switches to filter traffic based on IP address, Port number, and protocol.
DMZAn isolated buffer zone between the external network (Internet) and the internal network, typically housing public-facing services (Web, Mail, DNS).
Firewall ZoneDivides the network into zones of different trust levels (e.g., Trust / Untrust / DMZ), with cross-zone traffic inspected by firewall policies.
MicrosegmentationSets security policies at the individual workload (VM / Container) level in virtualized or cloud environments, a core principle of Zero Trust architecture.

VLAN Security

VLAN (Virtual Local Area Network) creates multiple logically independent network segments on the same physical switch, allowing traffic from different departments (e.g., Finance VLAN 10, Engineering VLAN 20) to remain isolated even when sharing the same physical infrastructure. The implementation standard is 802.1Q, which adds a 4-byte VLAN Tag to Ethernet frames, allowing switches to determine which segment a packet belongs to.

Port Types

Terminal devices (computers) send Ethernet frames without VLAN tags, but switches must know which VLAN a frame belongs to when forwarding. Port types determine how the switch handles these tags at each connection point.

TypeConnectionDescription
Access PortTerminal devicesBelongs to a single VLAN. Terminal devices send untagged frames; the switch adds the 802.1Q Tag upon ingress and strips it upon egress.
Trunk PortSwitch-to-switch, switch-to-routerCarries traffic for multiple VLANs. Frames are transmitted in tagged 802.1Q format; the tag is preserved across the trunk link.
Native VLANThe VLAN assigned to untagged frames on a Trunk Port (default is VLAN 1). Used for compatibility with legacy devices. Attackers can exploit this for Double Tagging attacks; the Native VLAN should be changed to an unused ID.
Scenario Comparison

Access Port — The Office Door Employees (terminal devices) don't need ID badges inside their own office. When an employee leaves the department, the guard at the door (Access Port) attaches a department badge (VLAN Tag); it's removed upon re-entry. The device is unaware of the badge.

Trunk Port — The Shared Elevator Finance and Engineering staff share the same elevator (Trunk Port). To identify everyone, they must wear department badges (Tagged) before entering. The elevator keeps the badges on. Upon arrival, the guard at the destination (another switch) sees the badge and knows where to direct them.

Native VLAN — The Person Without a Badge If someone enters the elevator without a badge (Untagged frame arrives at Trunk Port), the building has a rule: they are assigned to the "Default Identity" (Native VLAN, default 1). Attackers can exploit this by adding two layers of tags; the switch strips the outer one, and the inner tag sends the traffic into an unauthorized VLAN (Double Tagging attack).

Frame Transmission Flow

Diagram

VLAN Hopping Attacks

Attackers exploit VLAN configuration flaws to cross boundaries and access unauthorized segments.

Double Tagging

Vulnerability Principle: Exploits the default behavior of switches to "automatically strip tags" when handling Native VLANs to smuggle malicious packets into unauthorized segments. This is a one-way blind attack.

Trigger Conditions:

  1. Topology: Must have 2 or more switches with a Trunk Port connection.
  2. Attacker Position: The attacker's port must belong to the same VLAN as the Trunk's Native VLAN (usually default VLAN 1).

Malicious Payload Structure: The attacker crafts a special frame with two 802.1Q tags: [Outer Tag: Native VLAN (e.g., VLAN 1)] + [Inner Tag: Target VLAN (e.g., VLAN 10)] + [Malicious Data].

Execution Pipeline:

  1. Switch 1 (Trigger): Receives the packet. Seeing "Outer Tag = Native VLAN," it triggers the default rule: strip the outer tag.
  2. Trunk (Smuggling Channel): The outer tag is stripped, exposing the [Inner Tag: VLAN 10], which is then transmitted across the trunk.
  3. Switch 2 (Forwarding Node): Receives the packet. Seeing only [Inner Tag: VLAN 10], it forwards it to the target host in VLAN 10.
Diagram

This attack is inherently one-way: the target's response follows the normal VLAN 10 path and cannot reach the attacker, so it is used for triggering actions (e.g., ARP poisoning, service probing) rather than data theft.

Switch Spoofing (Trunk Spoofing) Most switches have DTP (Dynamic Trunking Protocol) enabled by default, which automatically negotiates Trunk connections. An attacker can send DTP negotiation messages to force the port into Trunk mode. Once successful, the attacker receives all tagged frames, rendering VLAN isolation useless.

DefenseTargetDescription
Change Native VLANDouble TaggingChange Native VLAN to an unused ID, preventing attackers from matching the outer tag
Disable DTPSwitch SpoofingExplicitly set ports to Access mode and disable auto-negotiation
Disable Unused PortsBothShutdown unused ports and assign them to an isolated VLAN

SDN Security (Software Defined Networking)

In traditional networks, every switch and router contains both a Control Plane (decision logic) and a Data Plane (packet forwarding). Updating security rules requires manual configuration on every device. SDN decouples the control plane, centralizing it in an SDN Controller, while devices only execute forwarding instructions.

Three-Layer Architecture

Diagram
ComponentDescription
Application LayerNetwork applications (e.g., load balancing) pass policies to the controller via Northbound APIs (REST).
Control LayerSDN Controller (e.g., OpenDaylight, ONOS) calculates global forwarding rules and pushes them to devices.
Infrastructure LayerSwitches/routers receive instructions via Southbound APIs (e.g., OpenFlow) and do not make independent routing decisions.
Scenario Comparison

Traditional networking is like having a guard in every room of a building, each with their own rulebook. Updating rules requires visiting every room; missing one creates a vulnerability.

SDN is like having a central control room. Guards no longer make decisions; they report to the control room, which makes the decision and sends instructions back to the guard.

  • Northbound API: Administrators (Application Layer) use an internal communication system (REST API) to tell the control room to "block this IP."
  • Southbound API: The control room uses a dedicated channel (OpenFlow) to send specific instructions to the guards on each floor.

Security Advantages:

  • Centralized Policy: Define security rules once on the controller and deploy them globally, ensuring consistency.
  • Dynamic Response: Detect abnormal traffic and have the controller instantly update rules across the network to isolate infected hosts.
  • Network Visibility: The controller has a global view of traffic, facilitating anomaly detection and forensics.

Security Risks:

  • Controller as Single Point of Failure: If the controller is compromised, the entire network's forwarding logic is controlled. Deploy HA clusters and strictly limit access.
  • Northbound API Attacks: If an attacker gains application-layer access, they can use the REST API to send malicious instructions. Implement API authentication and authorization.
  • Southbound API Attacks: If an attacker injects forged OpenFlow messages, they can manipulate forwarding rules. Communication between the controller and devices must be encrypted with TLS.

IPv6 Security Considerations

IPv4 uses 32-bit addresses (approximately 4.3 billion), which have long been exhausted. IPv6 expands the address space to 128 bits (approximately 3.4×10³⁸), serving as the long-term replacement. Due to the massive existing IPv4 infrastructure, most networks are currently in a Dual Stack transition period, running both IPv4 and IPv6 simultaneously. This parallel state introduces new security considerations: if security policies are designed only for IPv4, IPv6 traffic becomes a blind spot.

In the IPv6 specification, IPsec is a required support (though not mandatory to enable), providing native end-to-end encryption capabilities—a built-in security advantage not present in IPv4.

Security RiskDescription
Dual Stack RiskWhen both IPv4 and IPv6 are enabled, if IPv6 lacks corresponding security policies (firewall rules, IDS signatures), attackers can bypass protections designed only for IPv4.
RA SpoofingIPv6 uses SLAAC for automatic address assignment, a process relying on RA messages sent by routers. Attackers can send forged RAs to set themselves as the default gateway, with effects similar to IPv4's ARP Spoofing.
IPv6 Tunnel AbuseTransition mechanisms like Teredo and 6to4 encapsulate IPv6 packets within IPv4 for transmission, potentially bypassing firewalls and IDS that do not support IPv6.
Address Reconnaissance DifficultyAn IPv6 /64 subnet contains 2⁶⁴ addresses, making traditional per-IP scanning infeasible. Attackers instead use DNS queries, multicast addresses, or EUI-64 (rules deriving IPv6 addresses from device MAC addresses) for reconnaissance.
Defensive MeasuresDescription
Block Unused IPv6 TrafficIf an organization has not yet deployed IPv6, explicitly block IPv6 traffic at the firewall, including ports used by Teredo and 6to4 tunnels, to avoid security blind spots.
Dual Stack Policy SynchronizationIf dual stack is deployed, firewall rules, IDS/IPS signatures, and logging must cover both IPv4 and IPv6; do not protect only one side.
Enable RA GuardEnable RA Guard on switches to allow only legitimate routers to send RA messages, blocking forged Router Advertisements.

💡 Glossary Quick Reference

  • SLAAC: Stateless Address Autoconfiguration — IPv6 devices do not require a DHCP server and automatically generate their own IP addresses via RA messages.
  • RA: Router Advertisement — Messages periodically broadcast by routers to inform devices in the network segment of the gateway address and network prefix.
  • EUI-64: Extended Unique Identifier (64-bit) — Converts a device's 48-bit MAC address into a 64-bit interface identifier, used to automatically generate the host portion of an IPv6 address.
  • Teredo / 6to4: IPv6 over IPv4 Tunneling Transition Mechanism — Encapsulates IPv6 packets within IPv4 for transmission, allowing pure IPv4 environments to connect to IPv6 networks.
  • RA Guard: Router Advertisement Guard — A switch feature that allows only specified legitimate router ports to send RA messages, preventing spoofing.
  • Dual Stack: A configuration where the same device has both IPv4 and IPv6 enabled; it is currently the most common transition deployment method.

Wireless Network Encryption Standards Comparison

The WPA (Wi-Fi Protected Access) series is the Wi-Fi Alliance's certification standard for wireless network security. Starting from the structural vulnerabilities of WEP (Wired Equivalent Privacy), it has evolved through WPA → WPA2 → WPA3 to progressively strengthen encryption and authentication mechanisms.

StandardEncryption AlgorithmAuthentication MethodKey LengthKnown WeaknessesCurrent Recommendation
WEPRC4Open/Shared Key40/104 bitIV reuse attacks, keys can be cracked in minutesDisable
WPATKIP (Improved RC4)PSK / 802.1X128 bitTKIP has Michael attacks; designed as a transition for WEPNot recommended
WPA2AES-CCMPPSK / 802.1X128 bitKRACK attack (Key Reinstallation Attack), can force Nonce reuseStill usable, but upgrade to WPA3
WPA3AES-GCMP / AES-CCMPSAE / 802.1X128/192 bitDragonblood attack (patched)Recommended

Known Weakness Explanations

  • IV Reuse Attack (WEP): WEP uses a 24-bit Initialization Vector (IV) with RC4 for stream encryption. The IV space is only 2²⁴ ≈ 16 million, which is quickly exhausted in busy networks, leading to reuse. When two packets use the same IV, XORing the ciphertexts cancels out the key stream, allowing the recovery of plaintext or the key.
  • Michael Attack (WPA/TKIP): TKIP (Temporal Key Integrity Protocol) is the encryption protocol for WPA, designed to patch WEP vulnerabilities without replacing old hardware. It still uses RC4 at the base but adds per-packet keys (to avoid IV reuse) and the Michael message integrity code (to prevent forgery). Michael's design is insufficiently strong; attackers can forge packets and pass validation in a short time. TKIP was an emergency transition scheme with inherent design limitations and was eventually replaced by WPA2's AES-CCMP.
  • KRACK (WPA2): Key Reinstallation Attack. Attackers replay message 3 of the 4-way handshake, forcing the client to reinstall the key and reset the Nonce to 0, causing Nonce reuse. Once the Nonce is reused, AES-CCMP encryption protection fails, allowing attackers to decrypt packets or forge data. See the 4-way handshake explanation below.
  • Dragonblood (WPA3/SAE): A side-channel attack targeting early SAE implementations, inferring passwords by measuring timing differences or cache access behavior during Dragonfly calculations. The Wi-Fi Alliance patched this in WPA3 Revision 1; current correct implementations are not affected.

WPA2 4-Way Handshake

The 4-way handshake confirms during connection that both parties hold the same PMK (Pairwise Master Key, derived from the passphrase) and negotiates the PTK (Pairwise Transient Key) for encrypting unicast data and the GTK (Group Temporal Key) for broadcast. The PMK itself is never transmitted over the network; both parties calculate it independently from the passphrase.

Diagram
KRACK Attack Flow

The attacker acts as a man-in-the-middle, intercepting message 4 (ACK) so the AP assumes the client did not receive message 3, causing the AP to retransmit message 3 per the protocol. Each time the client receives message 3, it reinstalls the key and resets the Nonce to 0. Once the Nonce is reused, the same key encrypts different packets, allowing the attacker to recover the key stream and decrypt or forge packets.

Diagram

WPA3 and SAE

WPA2 vs WPA3 Core Differences:

AspectWPA2WPA3
Key Exchange4-Way Handshake (PSK)SAE (Dragonfly protocol)
Offline Dictionary AttackPossible (crack offline after capturing handshake)Impossible (requires interaction for each handshake)
Forward Secrecy (PFS)Not supportedSupported (SAE generates independent session keys)
Open NetworkNo encryptionOWE (Opportunistic Wireless Encryption)
Enterprise SecurityWPA2-EnterpriseWPA3-Enterprise (192-bit CNSA suite)

SAE (Simultaneous Authentication of Equals)

SAE is based on the Dragonfly key exchange protocol (RFC 7664). The core idea of Dragonfly is to map the password to a point on an elliptic curve (PWE, Password Element) and perform key exchange based on this; the password itself is never transmitted over the network and leaves no material for offline comparison. Attackers must initiate a full handshake interaction for every guess, unlike WPA2, where one captured packet allows infinite offline password guessing.

SAE handshake consists of two phases:

  • Commit Phase: Both parties map the password and MAC address to a PWE on the elliptic curve, generate a random private value, calculate a scalar and element, and exchange them. Even if an attacker captures these public values, they cannot verify password guesses without interacting with the parties.
  • Confirm Phase: Both parties calculate a confirmation code using the negotiated shared key and verify it with each other to ensure both know the correct password, completing mutual authentication.
Diagram

OWE (Opportunistic Wireless Encryption)

OWE is used for passwordless open networks (e.g., coffee shop Wi-Fi). Traditional open networks have no encryption, allowing anyone on the same network to eavesdrop. OWE allows each client and AP to perform an ECDH key exchange during connection, establishing an independent encrypted channel for that connection to prevent passive eavesdropping.

OWE does not verify AP identity (open networks have no password to bind to an AP), so it cannot prevent Evil Twin Attacks; it only provides eavesdropping protection, not identity authentication.

WPA3 Version Notes:

VersionUse CaseCore Features
WPA3-PersonalHome / Small OfficeSAE replaces PSK, provides PFS
WPA3-EnterpriseGovernment / High-security environmentsSupports 192-bit security suite (CNSA, Commercial National Security Algorithm)
OWEPublic Wi-Fi (Open Network)Establishes independent encrypted channel for each user, no password required

Purdue Model (OT / ICS Layered Security Architecture)

The Purdue Model (Purdue Enterprise Reference Architecture, PERA) is a security layering reference architecture for Industrial Control Systems (ICS / OT), dividing the OT environment into six levels (Level 0–5) based on function, clearly specifying equipment, functions, and security isolation requirements for each level.

LevelNameEquipment / FunctionDescription
Level 0Field DevicesSensors, Actuators, MotorsThe lowest-level hardware directly controlling physical processes
Level 1ControlPLC, RTU, DCSReceives sensor signals and controls actuators based on logic
Level 2SupervisorySCADA, HMIOperator interface for monitoring and controlling Level 1 devices; security incidents often spread from this level
Level 3Manufacturing OperationsMES, Historian data collection serversScheduling, production tracking, recording manufacturing data
Level 3.5 (iDMZ)Industrial DMZProxy, Jump Server, Data Diode, FirewallBuffer isolation zone between OT (Level 3) and IT (Level 4); ensures no direct network connection between IT and OT. All data exchange must pass through proxies or jump servers within the iDMZ, effectively preventing IT-layer malware from directly accessing the OT core.
Level 4–5Enterprise and External NetworksERP, Business Systems, InternetTraditional IT environment

OT Security Key Principles

  • The boundary between Level 1 (PLC/RTU) and Level 2 (SCADA/HMI) is the most common lateral movement path for attackers: after compromising SCADA (Level 2), they can send commands downward to directly affect physical processes at Level 1 (e.g., the Ukraine power grid attack).
  • iDMZ (Industrial DMZ): Corresponds to Level 3.5, the necessary buffer isolation zone between OT and IT; data should be transmitted unidirectionally through proxies or Data Diodes in the iDMZ to prevent IT-side threats from entering OT directly.
  • Purdue vs Zero Trust: Zero Trust requires identity verification for every request, but many PLC devices in OT environments lack authentication capabilities. Therefore, Zero Trust in OT is primarily implemented as network boundary control between Level 3 and 4.

💡 Glossary Quick Reference

  • IT: Information Technology — Computer systems handling data, communication, and business logic, such as servers, databases, and ERP. The core difference from OT is that IT prioritizes Confidentiality, while OT prioritizes Availability.
  • OT: Operational Technology — Hardware and software systems directly controlling physical equipment and industrial processes.
  • ICS: Industrial Control System — The umbrella term for OT, covering control systems like PLC and SCADA.
  • PLC: Programmable Logic Controller — Industrial computer that receives sensor signals and controls actuators based on configured logic.
  • RTU: Remote Terminal Unit — Data acquisition and control equipment deployed in the field that communicates with SCADA.
  • DCS: Distributed Control System — Industrial control architecture distributing control functions to multiple nodes, commonly used in large manufacturing plants.
  • SCADA: Supervisory Control and Data Acquisition — System for centralized monitoring of multiple field devices; operators monitor and control via HMI interfaces.
  • HMI: Human Machine Interface — Graphical interface for operators to interact with industrial control systems.
  • MES: Manufacturing Execution System — Information system managing production scheduling and tracking manufacturing progress.
  • ERP: Enterprise Resource Planning — Management system integrating enterprise resources like finance, HR, and supply chain; belongs to the IT side.
  • Data Diode: Hardware device allowing data to flow in only one direction, commonly used at the OT/IT boundary to prevent external threats from entering the OT network.

Linux / Windows Network Security Tools Comparison

Firewall Configuration

FeatureWindowsLinux
Built-in FirewallWindows Defender Firewalliptables / nftables / firewalld
CLI Managementnetsh advfirewall / PowerShell New-NetFirewallRuleiptables / nft / firewall-cmd
GUI Managementwf.msc (Windows Firewall with Advanced Security)Cockpit Web Console / UFW (Uncomplicated Firewall)
Rule PersistenceAutomatically savediptables requires iptables-save / iptables-restore; firewalld uses XML config files for persistence

Linux Firewall Evolution

  • iptables: The classic packet filtering tool for Linux 2.4+, based on the Netfilter framework. Rules are organized by Chains and Tables.
  • nftables: Introduced in Linux 3.13+, the successor to iptables. It has more unified syntax and better performance, and is gradually replacing iptables.
  • firewalld: The default dynamic firewall management tool for RHEL / CentOS / Fedora, which can use iptables or nftables as the backend. It supports the concept of Zones and real-time rule changes.
iptables / nftables Firewall Rule Examples

Common iptables rules

bash
# Allow established connections and related traffic
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# Allow SSH (Port 22)
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Allow HTTPS (Port 443)
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Default deny all inbound traffic
iptables -P INPUT DROP

# Save rules (Debian/Ubuntu)
iptables-save > /etc/iptables/rules.v4

Equivalent nftables rules

bash
# Create table and chain
nft add table inet filter
nft add chain inet filter input { type filter hook input priority 0 \; policy drop \; }

# Allow established connections
nft add rule inet filter input ct state established,related accept

# Allow SSH and HTTPS
nft add rule inet filter input tcp dport { 22, 443 } accept

# Save rules
nft list ruleset > /etc/nftables.conf

Network Diagnostic Tools

FeatureWindowsLinuxDescription
IP Config Queryipconfig / ipconfig /allip addr / ifconfig (deprecated)View network adapter IP, subnet mask, and gateway.
Connection Statusnetstat -anss -tulnp / netstat -tulnpView current TCP/UDP connections and listening ports. ss is the modern replacement for netstat.
Route Tracingtracerttraceroute / mtrTrace the hop path of packets to the destination. mtr combines ping and traceroute.
DNS Querynslookup / Resolve-DnsNamedig / nslookupUse nslookup for general queries; for DNSSEC records, see the centralized examples in the DNS Security section.
ARP Table Queryarp -aip neigh / arp -aView local ARP cache.
Common Network Diagnostic Command Examples
bash
# Trace route (find where packets are dropped or latency spikes)
tracert 8.8.8.8                     # Windows
traceroute 8.8.8.8                  # Linux

# View listening ports (confirm which services are exposed)
netstat -ano | findstr LISTENING    # Windows
ss -tulnp                           # Linux (-t TCP, -u UDP, -l listening, -n no name resolution, -p show process)

0.0.0.0 / 127.0.0.1 / localhost Confusing Security Traps

AddressSemanticsSecurity Risk
127.0.0.1Loopback address, packets do not leave the hostService is local-only, cannot be accessed externally.
localhostHostname, defaults to 127.0.0.1 (or ::1 in IPv6)/etc/hosts can be tampered with to point elsewhere; in dual stack, if firewall only blocks 127.0.0.1, ::1 might be missed.
0.0.0.0Server binding context: listen on all network interfaces, including external onesMisuse during development exposes local-only services directly to the internet.

Common traps:

  • Development databases (Redis, MySQL) bound to 0.0.0.0 and deployed without external firewall protection, exposing them to the public internet.
  • 127.0.0.1 inside a container is local to the container; the host cannot access it. If host access is needed, explicitly bind to 0.0.0.0 or the host IP, combined with firewall source IP restrictions.

Network Sniffing and Packet Capture

ToolPlatformDescription
WiresharkWindows / Linux / macOSGUI packet analysis tool, supports hundreds of protocol dissectors.
tcpdumpLinux / macOSCLI packet capture tool, lightweight and efficient, suitable for server environments.
tsharkWindows / Linux / macOSCLI version of Wireshark, suitable for script automation.
Common tcpdump Commands
bash
# Capture all traffic on eth0 interface
tcpdump -i eth0

# Capture only HTTPS traffic (Port 443)
tcpdump -i eth0 port 443

# Capture traffic for a specific host
tcpdump -i eth0 host 192.168.1.100

# Capture TCP SYN packets (first step of 3-way handshake)
tcpdump -i eth0 'tcp[tcpflags] & tcp-syn != 0'

# Save capture results to pcap file (for Wireshark analysis)
tcpdump -i eth0 -w capture.pcap -c 1000

# Read pcap file
tcpdump -r capture.pcap

# Exclude SSH traffic (avoid capturing your own remote connection)
tcpdump -i eth0 not port 22
Common Wireshark Display Filter Syntax
text
# Filter by protocol
http
dns
tls
tcp
arp

# Filter by IP address
ip.addr == 192.168.1.100
ip.src == 10.0.0.1
ip.dst == 172.16.0.0/12

# Filter by Port
tcp.port == 443
tcp.dstport == 80

# Filter by HTTP method
http.request.method == "POST"

# Filter by DNS query name
dns.qry.name == "example.com"

# Filter by TLS version
tls.handshake.version == 0x0304  # TLS 1.3

# Filter by TCP Flag
tcp.flags.syn == 1 && tcp.flags.ack == 0  # SYN (new connection)
tcp.flags.reset == 1                       # RST (connection reset)

# Combine conditions
ip.addr == 192.168.1.0/24 && tcp.port == 443 && tls
  • Display Filter: Filters displayed packets from an existing capture; syntax as above.
  • Capture Filter: Filters during capture; syntax is BPF (Berkeley Packet Filter), same as tcpdump (e.g., host 192.168.1.100 and port 443).

Cryptography

Cryptography and Data Protection Technology Comparison

Technology CategoryKey CountSpeedCore PurposeCommon Algorithms
Symmetric1 (shared for encryption/decryption)Extremely fastBulk data, files, full disk encryptionAES, DES, RC4
Asymmetric2 (public encrypt/private decrypt; private sign/public verify)Extremely slowKey exchange (sending symmetric keys), digital signatures, authenticationRSA, ECC (Elliptic Curve)
Hash FunctionNone (one-way, irreversible)FastPassword storage (with Salt), data integrity verificationSHA-2 (e.g., SHA-256, SHA-512), MD5 (deprecated)

Symmetric vs Asymmetric Encryption Flow Comparison

Diagram

Symmetric Encryption Block Modes (ECB / CBC / CTR / GCM)

Symmetric encryption processes data in fixed-size "blocks," and the "mode" determines how blocks are chained and computed. Security differences between modes are significant.

ModeFull NameParallelizableSecurityDescription
ECBElectronic CodebookIdentical plaintext blocks produce identical ciphertext, leaking data patterns (e.g., image contours remain visible after encryption)
CBCCipher Block Chaining⚠️Previous ciphertext block XORed with next plaintext; eliminates ECB pattern leakage; not parallelizable, has POODLE (Padding Oracle On Downgraded Legacy Encryption) vulnerability
CTRCounter ModeConverts block encryption to stream encryption, parallelizable, high performance
GCMGalois/Counter Mode✅ RecommendedCTR encryption + GMAC (Galois Message Authentication Code) integrity verification; an AEAD (Authenticated Encryption with Associated Data) mode; mainstream choice for TLS 1.2+ (AES-GCM)

Why ECB Mode is Insecure

ECB mode encrypts each block independently, so identical plaintext blocks always produce identical ciphertext blocks. This leaks structural patterns: encrypting a Linux Tux image with ECB mode still clearly reveals the penguin's outline; switching to CBC / GCM results in complete noise. ECB mode should not be used in any scenario.

ECB mode penguin image visual comparison

Nonce and IV (Initialization Vector)

ConceptFull NameDescription
IVInitialization VectorIn modes like CBC/CFB, XORed with the first plaintext block before encryption to ensure identical plaintext produces different ciphertext in different operations
NonceNumber Used OnceIn modes like CTR/GCM, used as the initial value for the counter; must never be reused (with the same key)

Core requirements for IV/Nonce vary by mode:

ModeRoleCore RequirementRecommended Length
ECBNone
CBCIVUnpredictable: Must be truly random; if predictable, attackers can launch chosen-plaintext attacks (BEAST attack exploits this to crack TLS Cookies)16 bytes
CTRNonceUnique: Must not repeat with the same key, randomness not strictly required; global counters are hard in distributed systems, so random numbers are recommended12 bytes
GCMNonce (Spec calls it IV)Same as CTR; 12 bytes (96-bit) directly forms the initial counter block J0 for best performance, official recommendation12 bytes

Nonce/IV do not need to be secret, send publicly with ciphertext

The Key must never be leaked, but the Nonce/IV is a public value used only to ensure each encryption result is unique. The receiver uses the Nonce + Key to decrypt; the standard practice is to send the Nonce along with the ciphertext.

Transmission MethodApproachUse Case
Prepended to Ciphertext (Most common)[Nonce (12 bytes)][Ciphertext], receiver slices first 12 bytesAPI transmission, file encryption
Separate Database ColumnStore EncryptedData and CryptoNonce in two columns, SELECT together for decryptionDatabase column encryption
HTTP Header / JWTPlace in X-Nonce Header or JWT PayloadAPI communication

Why GCM prefers 12-byte Nonce

  • GCM's underlying block size is 128-bit. When the IV/Nonce is exactly 96-bit (12 bytes), the spec can directly form J0 = IV || 0^31 || 1, adding a 32-bit counter tail to form a complete 128-bit initial block.
  • Subsequent counter increments only need to operate on the right-hand 32-bit counter, making this the most natural and efficient approach for GCM.
  • If the IV is not 96-bit, GCM must first map the IV to J0 via GHASH, adding an extra operation, increasing implementation complexity and usually reducing performance.
  • The core risk remains reusing the Nonce with the same key. Non-12-byte lengths are not necessarily insecure, but 96-bit is the standard choice for best interoperability and performance.

The Disaster of Nonce Reuse

CTR / GCM encryption is essentially stream encryption ( is XOR, bitwise comparison, same=0, different=1):

KS = KeyStream(Key, Nonce)    ← Determined entirely by Key and Nonce
Ciphertext = Plaintext ⊕ KS

If Key and Nonce are the same, the KS is identical. If an attacker obtains two ciphertexts encrypted with the same key and Nonce:

C1 = P1 ⊕ KS
C2 = P2 ⊕ KS

C1 ⊕ C2 = P1 ⊕ P2    ← KS cancels out, the key disappears

Specific Recovery Process

Assume an attacker captures two ciphertexts (e.g., after KRACK forces a Nonce reset, both packets are encrypted with Nonce = 0):

PlaintextHexDescription
P1"GET "47 45 54 20HTTP request start (including trailing space, 4 bytes), fixed format, attacker knows this
P2PASS50 41 53 53Target plaintext, attacker wants to know
KSA3 F2 1C 8BKey stream, attacker does not know

Ciphertexts seen by the attacker:

C1 = 47⊕A3  45⊕F2  54⊕1C  20⊕8B  =  E4 B7 48 AB
C2 = 50⊕A3  41⊕F2  53⊕1C  53⊕8B  =  F3 B3 4F D8

Attacker calculates C1 ⊕ C2, KS cancels out:

E4⊕F3  B7⊕B3  48⊕4F  AB⊕D8  =  17 04 07 73  =  P1 ⊕ P2

Restore P2 using known P1 ("GET "):

17⊕47  04⊕45  07⊕54  73⊕20  =  50 41 53 53  =  "PASS"

The attacker never obtained the key but fully restored P2.

GCM is even worse: When the Nonce is reused, not only is plaintext leaked, but the attacker can derive the GMAC authentication key H, allowing them to forge arbitrary packets that pass integrity checks. Encryption and authentication both fail. WPA2's KRACK attack exploits this principle.

C# Example: AES-GCM Encryption/Decryption
csharp
using System.Security.Cryptography;
using System.Text;

// --- Encryption ---
byte[] key = RandomNumberGenerator.GetBytes(32); // 256-bit key
byte[] nonce = RandomNumberGenerator.GetBytes(AesGcm.NonceByteSizes.MaxSize); // 12 bytes
byte[] plaintext = Encoding.UTF8.GetBytes("Confidential data: account, password, and PII");
byte[] ciphertext = new byte[plaintext.Length];
byte[] tag = new byte[AesGcm.TagByteSizes.MaxSize]; // 16 bytes
byte[] associatedData = Encoding.UTF8.GetBytes("metadata-v1"); // Associated authentication data (not encrypted but integrity verified)

using (AesGcm aesGcm = new(key, AesGcm.TagByteSizes.MaxSize)) {
    aesGcm.Encrypt(nonce, plaintext, ciphertext, tag, associatedData);
}

Console.WriteLine($"Nonce:      {Convert.ToBase64String(nonce)}");
Console.WriteLine($"Ciphertext: {Convert.ToBase64String(ciphertext)}");
Console.WriteLine($"Tag:        {Convert.ToBase64String(tag)}");

// --- Decryption ---
byte[] decrypted = new byte[ciphertext.Length];

using (AesGcm aesGcm = new(key, AesGcm.TagByteSizes.MaxSize)) {
    aesGcm.Decrypt(nonce, ciphertext, tag, decrypted, associatedData);
}

Console.WriteLine($"Decrypted:  {Encoding.UTF8.GetString(decrypted)}");

Asymmetric Encryption Algorithms

Asymmetric encryption uses a pair of public and private keys to handle two types of tasks: "encryption/decryption" and "signature verification." The current mainstream algorithms are RSA and ECC, both of which are built upon different mathematically difficult problems.

AspectRSAECC (Elliptic Curve Cryptography)
Mathematical BasisDifficulty of large integer factorizationECDLP (Elliptic Curve Discrete Logarithm Problem)
Key Length for Equivalent Security2048-bit or 3072-bit256-bit (≈ RSA 3072-bit)
Computational SpeedSlower (slower as keys get longer)Faster (shorter keys achieve equivalent security)
Key and Signature SizeLarger (consumes more bandwidth and storage)Smaller, suitable for bandwidth or storage-constrained environments
Applicable ScenariosTraditional PKI (Public Key Infrastructure), systems requiring backward compatibilityIoT (Internet of Things) devices, mobile devices, TLS 1.3
Main AlgorithmsEncryption: RSA-OAEP (Optimal Asymmetric Encryption Padding)
Signature: RSA-PSS (Probabilistic Signature Scheme)
Signature: ECDSA (Elliptic Curve Digital Signature Algorithm)
Key Exchange: ECDH (Elliptic Curve Diffie-Hellman) / ECDHE (Ephemeral version)

Trade-offs between ECC and RSA

  • Why ECC has clear advantages but RSA remains mainstream: Existing PKI infrastructure, HSMs (Hardware Security Modules), and legacy compliance standards are mostly built around RSA. While ECC is the default choice for new systems (TLS 1.3 mandates ephemeral key exchange, with ECDHE being the mainstream), the large volume of legacy systems makes a full replacement difficult in the short term.
  • TLS 1.3 mandates ephemeral key exchange (ECDHE / DHE) and no longer supports static RSA key exchange.
  • Quantum Computer Threat: Both RSA and ECC could be cracked by Shor's Algorithm. Post-Quantum Cryptography (PQC) is currently being standardized (NIST released the first batch of PQC standards in 2024).
  • Security strength equivalence: ECC 256-bit ≈ RSA 3072-bit ≈ Symmetric encryption 128-bit.
C# Example: RSA Encryption/Decryption and Digital Signature
csharp
using System.Security.Cryptography;
using System.Text;

// --- Generate RSA Key Pair ---
using RSA rsa = RSA.Create(2048);
byte[] publicKey = rsa.ExportRSAPublicKey();
byte[] privateKey = rsa.ExportRSAPrivateKey();

// === Encryption/Decryption (Public Key Encrypt → Private Key Decrypt) ===
byte[] plaintext = Encoding.UTF8.GetBytes("Confidential Data");

using RSA rsaEncryptor = RSA.Create();
rsaEncryptor.ImportRSAPublicKey(publicKey, out _);
byte[] encrypted = rsaEncryptor.Encrypt(plaintext, RSAEncryptionPadding.OaepSHA256);
Console.WriteLine($"Encrypted: {Convert.ToBase64String(encrypted)}");

using RSA rsaDecryptor = RSA.Create();
rsaDecryptor.ImportRSAPrivateKey(privateKey, out _);
byte[] decrypted = rsaDecryptor.Decrypt(encrypted, RSAEncryptionPadding.OaepSHA256);
Console.WriteLine($"Decrypted: {Encoding.UTF8.GetString(decrypted)}");

// === Digital Signature (Private Key Sign → Public Key Verify) ===
byte[] document = Encoding.UTF8.GetBytes("Contract Content v1.0");

using RSA rsaSigner = RSA.Create();
rsaSigner.ImportRSAPrivateKey(privateKey, out _);
byte[] signature = rsaSigner.SignData(
    document,
    HashAlgorithmName.SHA256,
    RSASignaturePadding.Pss
);
Console.WriteLine($"Signature: {Convert.ToBase64String(signature)}");

using RSA rsaVerifier = RSA.Create();
rsaVerifier.ImportRSAPublicKey(publicKey, out _);
bool isValid = rsaVerifier.VerifyData(
    document,
    signature,
    HashAlgorithmName.SHA256,
    RSASignaturePadding.Pss
);
Console.WriteLine($"Signature verification result: {isValid}");
C# Example: ECDSA Digital Signature
csharp
using System.Security.Cryptography;
using System.Text;

// --- Generate ECDSA Key Pair (P-256 Curve) ---
using ECDsa ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256);
byte[] publicKey = ecdsa.ExportSubjectPublicKeyInfo();
byte[] privateKey = ecdsa.ExportPkcs8PrivateKey();

// --- Sign ---
byte[] document = Encoding.UTF8.GetBytes("Transaction Record #20250101-001");
byte[] signature = ecdsa.SignData(document, HashAlgorithmName.SHA256);
Console.WriteLine($"Signature: {Convert.ToBase64String(signature)}");

// --- Verify (Simulate receiver only having the public key) ---
using ECDsa verifier = ECDsa.Create();
verifier.ImportSubjectPublicKeyInfo(publicKey, out _);
bool isValid = verifier.VerifyData(document, signature, HashAlgorithmName.SHA256);
Console.WriteLine($"ECDSA signature verification result: {isValid}");

// --- Key Size Comparison ---
Console.WriteLine($"ECDSA P-256 public key size: {publicKey.Length} bytes");
Console.WriteLine($"ECDSA P-256 signature size: {signature.Length} bytes");
Application Layer Cryptography Practice (Extra protection beyond TLS)

If TLS is correctly implemented (enforcing TLS 1.2+ and valid certificates), it already provides sufficient transport encryption. The following approach is suitable for scenarios with compliance requirements or needs for defense-in-depth.

Recommended Workflow: Backend generates time-limited asymmetric key pair

  1. When the frontend enters the login page, it calls a backend API to obtain a temporary public key.
  2. The backend generates an RSA key pair, stores the private key in temporary storage with a TTL (Time To Live), and returns only the public key.
  3. The frontend encrypts the password with the public key and sends it.
  4. The backend decrypts it with the corresponding private key, verifies the login, and destroys the private key immediately after decryption.

Private Key Temporary Storage Options:

OptionApplicable ConditionsNotes
Redis (Recommended)Multi-instance or Redis environmentTTL expires automatically, supports horizontal scaling
Application MemorySingle-instance, no RedisKeys lost after application restart, cannot be shared across instances
DatabaseNone of the above are feasibleRequires manual cleanup of expired keys, not the first choice

Key Validity: Recommended 5–15 minutes, and designed for single-use (invalidated immediately after successful decryption) to prevent Replay Attacks.

Key Expiration Handling: Frontend re-fetches

When the backend returns an error indicating the key does not exist or has expired, the frontend calls the API again to obtain a new public key and retries. It is not recommended to keep an overlap period for the previous key: login is a one-time, short-lived operation; an overlap period increases implementation complexity without significant user experience benefits, and having two valid private keys simultaneously expands the exposure window.

Why use asymmetric instead of symmetric?

Symmetric encryption requires the frontend and backend to share a key. A static key written in the frontend source code is equivalent to plaintext; if dynamically issued by the backend, the delivery process itself faces the same protection problem (chicken-and-egg). The public key of asymmetric encryption can be public; even if intercepted, it can only be used to encrypt, not decrypt, and the private key always remains on the backend.

Why fetch the public key via API instead of a static public key file?

Static public keys require replacement via deployment. In a frontend-backend decoupled architecture, this also requires coordinating frontend deployment timing (if the frontend is maintained by different teams or vendors, the rotation cost is higher), leading to longer rotation cycles and a larger exposure window if the key is leaked. The API approach allows for mandatory expiration and single-use settings, and keys can be rotated without redeployment.

Hash Function

A hash function converts input of any length into a fixed-length output (digest) and possesses four core characteristics:

  • One-wayness: It is impossible to derive the original input from the output.
  • Determinism: The same input always produces the same output.
  • Avalanche Effect: If the input changes by even one bit, the output will be completely different.
  • Collision Resistance: It is difficult to find two different inputs that produce the same output (collision).

Main uses: Data integrity verification, digital signatures (signing the digest rather than the original text, see Digital Signature section for details), and password storage.

Fast Hash Algorithms

Fast hashes are designed for speed and are suitable for integrity verification and digital signatures. The mainstream algorithms are the SHA family:

  • MD5 / SHA-1: Actual collision attacks have been discovered; they should no longer be used in security scenarios (digital signatures, certificate issuance). If only detecting accidental data corruption (not malicious tampering), MD5 is technically still usable, but new systems should avoid it.
  • SHA-2 (SHA-256, SHA-384, SHA-512): Current mainstream standard, widely used in TLS, digital signatures, and certificates. The number suffix indicates the output bit length (SHA-256 outputs a fixed 256 bits, SHA-512 outputs a fixed 512 bits), regardless of input size.
  • SHA-3: Another design architecture (based on the Keccak sponge function, unrelated to SHA-2), used as an alternative standard, though less common.

Hash Collision: Two different inputs produce the same hash output. A collision itself does not allow an attacker to reverse-engineer a password, but it allows an attacker to forge a fake document with the same hash value as the original, which is fatal to the security of digital signatures.

C# Example: SHA-256 Hash Verification (Integrity Verification)
csharp
using System.Security.Cryptography;
using System.Text;

byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes("Important document content"));
Console.WriteLine(Convert.ToHexStringLower(hash));

// Verify integrity: Compare hash values of two pieces of data
byte[] hash2 = SHA256.HashData(Encoding.UTF8.GetBytes("Important document content"));
Console.WriteLine($"Integrity consistent: {CryptographicOperations.FixedTimeEquals(hash, hash2)}");

Salt vs. Pepper Comparison:

MechanismStorage LocationUnique per data?Description
SaltDatabase (same table as hash)✅ Unique per entryA random salt value for each user, preventing Rainbow Table Attacks
PepperEnvironment Variable / Secrets Manager (not in DB)❌ Globally sharedA global secret value; even if the entire database is leaked, passwords cannot be recovered without the pepper

They can be used together: hash(password + Salt + Pepper). Salt is stored in the database, Pepper is stored in external system configuration.

  • Extension: Can asymmetric encryption also be unique per entry? The concept is feasible, but a private key is different from a Salt and cannot be stored in the database in plaintext; otherwise, if the database is leaked, all private keys are leaked, rendering encryption useless.
Origin of the names Salt and Pepper

These two terms originate from a culinary metaphor: "Adding ingredients to the password makes it harder for attackers to taste the original flavor."

  • Salt: First proposed by Robert Morris and Ken Thompson in the 1970s in the Unix password system. Mixing a random value into the password before hashing ensures that the same password produces different hash values, rendering rainbow tables (pre-computed hash lookup tables) ineffective.
  • Pepper: A later extended concept, corresponding to "another seasoning." Unlike salt, which is kept on the table (database), pepper is hidden in the kitchen safe (environment variable), so even if the table is overturned, it cannot be found.

Slow Hash Algorithms (Key Stretching)

Key Stretching deliberately increases computational costs to make brute-force attacks infeasible. The following is a comparison of mainstream slow hash algorithms:

AlgorithmCore MechanismAdjustable ParametersMemory RequirementAnti-GPU/ASICNotes
PBKDF2Repeated HMAC (e.g., HMAC-SHA256)Iteration countLow.NET built-in (Rfc2898DeriveBytes); NIST recommended; OWASP suggests at least 600,000 iterations (SHA-256)
bcryptBased on Blowfish block cipherCost FactorMedium (4 KB)⚠️Mature design, widely used; input limited to 72 bytes
scryptPBKDF2 + heavy memory accessN (CPU/memory cost), r, pHigh (adjustable)Memory-intensive design resists ASIC; parameter tuning is complex
Argon2Memory-intensive + optional multi-threadingMemory, iterations, parallelismHigh (adjustable)2015 PHC (Password Hashing Competition) winner; divided into Argon2d (anti-GPU), Argon2i (anti-side-channel), Argon2id (hybrid, recommended)

Selection Recommendations

The core threat that slow hashing counters is "offline GPU brute-force." GPUs have thousands of computing cores, and relying solely on iteration counts to slow down the CPU has limited effect. Memory-Hardness is the key; if each calculation requires a large amount of memory (e.g., 64MB), the GPU's VRAM becomes the bottleneck (16GB VRAM ÷ 64MB = at most 256 parallel instances).

Selection Priority:

  1. Argon2id (First Choice): Memory, iterations, and parallelism are all adjustable; combines the advantages of Argon2d (anti-GPU/ASIC) and Argon2i (anti-side-channel). OWASP recommends minimum parameters: 64MB memory, 3 iterations, 4 parallelism.
  2. bcrypt (Second Choice): Mature, reliable, widely supported; memory requirement is only 4KB, but has a 72-byte input length limit.
  3. scrypt: Memory requirement is higher than bcrypt, but the three parameters (N / r / p) are complex to tune, making it less commonly used in practice.
  4. PBKDF2 (Constrained Scenarios): No memory hardening; only selected under FIPS compliance or .NET built-in API limitations.

All algorithms must be used with a random Salt to prevent rainbow table attacks.

Why NIST recommends PBKDF2, and .NET has no built-in Argon2 / bcrypt

Why NIST recommends PBKDF2

NIST's cryptographic standards are based on FIPS 140 compliance. PBKDF2 uses HMAC-SHA256 or HMAC-SHA512 at its core, both of which are NIST-defined standards that fully comply with the FIPS whitelist. bcrypt uses the Blowfish block cipher (not a FIPS-approved algorithm); Argon2 uses Blake2b (not included in the FIPS core cryptographic module).

PBKDF2 lacks memory hardening, so NIST's corresponding approach is to require a significant increase in iteration counts. OWASP suggests at least 600,000 iterations (HMAC-SHA256) to compensate for the lack of memory hardness, which mathematically provides sufficient security while maintaining FIPS compliance.

Why .NET BCL has no built-in Argon2 / bcrypt

Three reasons:

  1. Limitations of OS native APIs: .NET's cryptographic classes (System.Security.Cryptography) prioritize calling underlying OS APIs (CNG on Windows, OpenSSL on Linux) rather than implementing them from scratch. Windows CNG has long lacked native support for Argon2 or bcrypt, so .NET lacks an official wrapper.
  2. Historical compatibility of ASP.NET Core Identity: The Identity framework was built on PBKDF2 (Rfc2898DeriveBytes) from the start. Changing the default algorithm would make password hashes in existing databases unverifiable. Microsoft chose to increase iteration counts generation by generation (.NET 8 defaults to hundreds of thousands) rather than replacing the algorithm directly.
  3. Design philosophy of a lean core: Modern .NET's strategy is to keep the core lightweight and leave domain-specific needs to open-source packages. Mature NuGet packages for Argon2 and bcrypt already exist (e.g., Konscious.Security.Cryptography.Argon2, BCrypt.Net-Next), so official inclusion is unnecessary.

PBKDF2's underlying structure

PBKDF2 code requires passing HashAlgorithmName.SHA256, which looks like processing a fast hash. This is a design unique to PBKDF2: it essentially executes HMAC-SHA256 repeatedly for a specified number of times (600,000 iterations). The "slowness" comes from the count, not because the underlying algorithm itself is slow.

The underlying mechanisms of bcrypt, scrypt, and Argon2 do not simply repeat a fast hash. bcrypt uses the Blowfish block cipher; scrypt adds a memory-mixing function on top of PBKDF2; Argon2 uses Blake2b as the computational unit for memory filling. This is the fundamental reason why PBKDF2 is more easily parallelized by GPUs than the other three, as GPUs are inherently good at executing large amounts of SHA operations in parallel.

C# Example: PBKDF2 Password Hashing and Verification
csharp
using System.Security.Cryptography;

// --- Generate Hash (during registration) ---
string password = "MySecureP@ssw0rd";
byte[] salt = RandomNumberGenerator.GetBytes(16);
int iterations = 600_000;
HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA256;
int keySize = 32; // 256 bits

byte[] hash = Rfc2898DeriveBytes.Pbkdf2(
    password,
    salt,
    iterations,
    hashAlgorithm,
    keySize
);

// Store in database: Base64(salt) + Base64(hash) + iterations
string saltBase64 = Convert.ToBase64String(salt);
string hashBase64 = Convert.ToBase64String(hash);
Console.WriteLine($"Salt: {saltBase64}");
Console.WriteLine($"Hash: {hashBase64}");

// --- Verify Password (during login) ---
string inputPassword = "MySecureP@ssw0rd";
byte[] storedSalt = Convert.FromBase64String(saltBase64);
byte[] storedHash = Convert.FromBase64String(hashBase64);

byte[] inputHash = Rfc2898DeriveBytes.Pbkdf2(
    inputPassword,
    storedSalt,
    iterations,
    hashAlgorithm,
    keySize
);

bool isValid = CryptographicOperations.FixedTimeEquals(inputHash, storedHash);
Console.WriteLine($"Password verification result: {isValid}");

Fast Hash vs. Slow Hash: Applicable Scenarios

Slow hashing has only one purpose: password storage. For other scenarios, a 100ms+ computational cost is a performance burden, not a security guarantee.

Fast HashSlow Hash
Computation TimeNanosecond level100ms or more
Password Storage❌ Easily brute-forced
Integrity / Verification / HMAC❌ Performance infeasible

Take JWT as an example: HS256 uses HMAC-SHA256 (fast hash) to sign the Header.Payload, and the signature must be re-calculated for every API request. If bcrypt were used, a single verification would take 100ms, and the server could only verify a few dozen tokens per second, making it impossible to serve.

Therefore, JWT uses fast hashes because the security threat models for JWT and passwords are different:

  • Passwords: After an attacker steals the hash from the database, they can perform unlimited offline brute-force enumeration; the slower it is, the harder the attack.
  • JWT HMAC: Requires holding the Secret key to generate a valid signature; without the key, even if one knows SHA-256 is used, it cannot be forged. Security relies on key secrecy, not hash speed.

MAC (Message Authentication Code)

A simple hash can only confirm whether a message "has been tampered with," but cannot confirm "who sent it." Because anyone can easily calculate a hash value, if an attacker intercepts and tampers with a message and then attaches a new hash value, the receiver cannot distinguish the truth.

MAC introduces a "shared secret key" on top of hashing, achieving two core security goals:

  • Data Integrity: Proves that the message has not been tampered with during transmission.
  • Source Authentication (Identity Authentication): Proves that the message indeed comes from an authorized party holding the same key.

Workflow:

  1. Sender: Inputs the "message" and "key" together into the calculation to generate a fixed-length verification tag, and sends it along with the message.
  2. Receiver: After receiving the message, uses their own copy of the same key to re-calculate the tag.
  3. Verification: If the calculated tag matches the received one, it means "the message is intact and the source is legitimate"; if they do not match, the message is rejected.

HMAC (Hash-based MAC)

HMAC is currently the most common MAC implementation, relying on standard hash functions (like SHA-256) at its core.

Why not just Hash(Key ‖ Message)? The most intuitive idea is to concatenate the key directly in front of the message and then hash it. However, this structure (Keyed-Hash) has a serious security vulnerability: even without knowing the key, an attacker can intercept the packet and "append" malicious content to the end of the original message, then use mathematical properties to calculate a new valid hash value (this technique is called Length Extension Attack).

To solve this problem, HMAC adopts a Nested Hash design architecture:

  • Inner operation: The key is XORed with the fixed constant ipad defined in RFC 2104 (0x36 × block length), concatenated with the message, and hashed once to get the inner digest.
  • Outer operation: The key is XORed with another fixed constant opad (0x5C × block length), concatenated with the inner digest, and hashed a second time to get the final tag.

The two constants are different, making the key derivation values for the inner and outer layers completely unrelated; the outer hash truncates the internal state of SHA-256, so an attacker cannot continue to extend from the final output, fundamentally immunizing against length extension attacks. The aforementioned XOR and two-layer hashing are all completed inside the HMAC implementation library; the caller only needs to pass K and M.

Formula: HMAC(K, M) = H((K ⊕ opad) ‖ H((K ⊕ ipad) ‖ M))

Symbol Explanation

  • : Concatenation, equivalent to A + B, joining two pieces of data head-to-tail.
  • : XOR (Exclusive OR), equivalent to A ^ B, comparing two pieces of data of equal length bit by bit; same is 0, different is 1.

Case: Integrity protection for API transfer requests

Suppose an API protects transfer requests with a shared key. Let's compare the differences between two MAC implementations regarding length extension attacks.

text
Shared key: K = "s3cr3tKey"
Original message: M = "amount=100&to=alice"

Option A — SHA256(K ‖ M) direct concatenation:

text
Sender calculates:
  Tag = SHA256("s3cr3tKey" ‖ "amount=100&to=alice")

Attacker intercepts packet, obtains (M, Tag)
SHA-256 uses Merkle–Damgård structure: final output = internal state after digesting all blocks
→ Holding Tag is equivalent to holding "the internal state of SHA-256 after digesting K ‖ M", which can be continued

  Append extra = "&override=9999&to=bob"
  NewTag = SHA256_continue(Tag, extra)
         ≡ SHA256("s3cr3tKey" ‖ "amount=100&to=alice" ‖ [padding] ‖ extra)
                                                                          ↑ No need to know K at all

Receiver verifies: SHA256(K ‖ tampered message) == NewTag  ← Matches perfectly, verification passes, attack successful

What is [padding]?

After processing the input data, SHA-256 automatically performs Merkle–Damgård padding at the end to meet the 512-bit block calculation requirement. Padding rules:

  1. Mark end: Append a 1 bit at the end of the message.
  2. Fill with zeros: Continue appending 0 bits until only the last 64 bits of the block remain.
  3. Record length: Write the total length of the original input into the last 64 bits.
[ Original Input K ‖ M ] [ 1 ] [ 00...padding...00 ] [ Original Length (64 bits) ]
|<---------------- Exactly a multiple of 512 bits ---------------->|

The padding content is uniquely determined by the original input length. The attacker only needs to know the length of K ‖ M to accurately calculate it, which is the fundamental reason why length extension attacks are feasible.

Option B — HMAC:

text
Sender calculates:
  inner = SHA256((K ⊕ ipad) ‖ M)       ← Fixed 256-bit inner digest
  Tag   = SHA256((K ⊕ opad) ‖ inner)   ← Outer layer wrapped again

Attacker also obtains (M, Tag), attempts to append extra, extending from Tag:

  Attacker expansion after extension:
    SHA256((K ⊕ opad) ‖ SHA256((K ⊕ ipad) ‖ M) ‖ [padding] ‖ extra)
                               └───────────────────┘
                               inner_old (contains only M), extra is in the outer layer

  True HMAC(K, M ‖ extra) expansion:
    SHA256((K ⊕ opad) ‖ SHA256((K ⊕ ipad) ‖ M ‖ extra))
                               └──────────────────────┘
                               inner_new (M ‖ extra enter the inner layer together)

  inner_old ≠ inner_new → Outer layer input is different → Verification must fail, attack ineffective

Not all integrity requirements need HMAC

The premise of HMAC is that both parties have already shared a secret key, introducing the burden of key management (distribution, rotation, revocation). If the scenario only requires "confirming whether the data has been changed" and does not need to confirm "who sent it," a hash function is sufficient:

RequirementSuitable MethodReason
Only need to confirm data integrity, mutual trustHash (SHA-256)No key needed, anyone can verify, no management burden
Need to confirm message comes from key holderHMACKey gives verification identity meaning
Need non-repudiation (third party can verify)Digital SignaturePublic/private key separation, private key holder cannot deny

Common "hash only" scenarios: File integrity verification (SHA-256 checksum), Git commit hash, Content-based Deduplication.

CMAC (Cipher-based MAC)

CMAC does not rely on hash functions but instead uses symmetric block ciphers (like AES) at the core to generate verification tags, standardized by NIST SP 800-38B.

Applicable Scenarios: In environments already equipped with hardware AES acceleration chips (such as HSM hardware security modules, IoT embedded devices, smart cards), using CMAC allows sharing the underlying AES computational unit, saving hardware resources, and highly complying with strict FIPS compliance requirements.

MAC vs. Digital Signature

MAC (HMAC)Digital Signature
Key TypeSymmetric (both share the same one)Asymmetric (private key signs, public key verifies)
Non-repudiation❌ (both can generate, cannot distinguish)✅ (only private key holder can sign)
Verification MethodRequires shared keyCan verify with public key, no prior sharing needed
SpeedFastSlow
Typical UseTLS key derivation (HKDF), JWT HS256, API request signingCertificates, code signing, contract signing
C# Example: HMAC-SHA256 Calculation and Verification
csharp
using System.Security.Cryptography;
using System.Text;

// --- Generate HMAC ---
byte[] key = RandomNumberGenerator.GetBytes(32); // 256-bit key
byte[] message = Encoding.UTF8.GetBytes("Transaction Amount: 50000, Account: 1234-5678");

byte[] hmac = HMACSHA256.HashData(key, message);
Console.WriteLine($"HMAC-SHA256: {Convert.ToBase64String(hmac)}");

// --- Verify HMAC (Receiver holds the same key) ---
byte[] receivedMessage = Encoding.UTF8.GetBytes("Transaction Amount: 50000, Account: 1234-5678");
byte[] computedHmac = HMACSHA256.HashData(key, receivedMessage);

bool isValid = CryptographicOperations.FixedTimeEquals(hmac, computedHmac);
Console.WriteLine($"HMAC verification result: {isValid}");

// --- Tamper Detection ---
byte[] tamperedMessage = Encoding.UTF8.GetBytes("Transaction Amount: 99999, Account: 1234-5678");
byte[] tamperedHmac = HMACSHA256.HashData(key, tamperedMessage);

bool isTampered = CryptographicOperations.FixedTimeEquals(hmac, tamperedHmac);
Console.WriteLine($"Tampered message verification result: {isTampered}"); // False

Digital Signature vs. General Encryption: Comparing Public/Private Key Usage

The two uses of asymmetric encryption have exactly opposite directions for public/private key usage:

General Encryption (Sending confidential data)

StepActionKey Used
1Sender encrypts original textReceiver's public key
2Receiver decryptsReceiver's private key

Purpose: Confidentiality (only the receiver holding the private key can read it)

Digital Signature (Verifying source and integrity)

StepActionKey Used
1Sender performs fast hash on original text (e.g., SHA-256) → Message Digest
2Sender encrypts digest with private key → Digital SignatureSender's private key
3Send "Original text + Digital Signature"
4Receiver decrypts signature with public key → Obtain Digest ASender's public key
5Receiver performs same fast hash on original text (e.g., SHA-256) → Obtain Digest B
6Compare Digest A and B → Match means verification passed

Purpose: Integrity + Non-repudiation (original text is sent in plaintext, confidentiality is not guaranteed)

Diagram

Common Misconceptions about Digital Signatures

  • Digital Signature ≠ Encryption: In the signature process, the original text is sent in plaintext, only guaranteeing "who sent it" and "whether it has been changed."
  • If both confidentiality + signature are needed: Sign first, then encrypt the whole thing with the receiver's public key (or symmetric key).
  • Why perform fast hash before signing? Asymmetric encryption is extremely slow; signing an entire document directly is impractical. The digest after a fast hash is a fixed length (e.g., SHA-256 = 256 bits), making signing much faster. Slow hashes are not used here because signatures require integrity and efficiency, not resistance to offline brute-force.

Digital Envelope

A digital envelope combines the advantages of symmetric and asymmetric encryption and is the most common hybrid encryption method in practice:

  1. The sender generates a one-time symmetric key (Session Key) and uses it to encrypt the data (fast).
  2. The sender uses the receiver's public key to encrypt the symmetric key (only encrypting the short key, which asymmetric encryption can handle).
  3. The encrypted data and the encrypted symmetric key are sent together.
  4. The receiver uses their private key to decrypt the symmetric key, then uses the symmetric key to decrypt the data.

Difference from digital signature:

MechanismProtection GoalKey Used
Digital EnvelopeConfidentiality (only receiver can read)Receiver's public key encrypts, receiver's private key decrypts
Digital SignatureIntegrity + Non-repudiation (confirm source)Sender's private key signs, sender's public key verifies

Key exchange in TLS handshakes is essentially an application of digital envelopes.

Diagram

When to use Symmetric vs. Asymmetric vs. Hybrid Encryption

ScenarioRecommended SolutionReason
Large data encryption (disk, file, database)Symmetric encryption (AES-GCM)Fast, suitable for large data
Key exchange, digital signatureAsymmetric encryption (RSA / ECC)Solves key distribution problem, provides identity verification
Network transmission (TLS, email encryption)Hybrid encryption (Digital Envelope)Combines advantages: asymmetric for key exchange + symmetric for data
Password storageKey Stretching (Argon2id / bcrypt)One-way hash, no decryption needed
Data integrity verificationHMAC / Digital SignatureHMAC for shared keys; signature for public verification

PKI (Public Key Infrastructure) Trust Chain

ComponentEnglishDescription
Root CARoot CAThe top of the trust chain; self-signed certificate, built into the trust list of browsers/operating systems.
Intermediate CAIntermediate CAIssued by the Root CA; acts as a proxy to issue end-entity certificates, reducing the risk of exposing the Root CA's private key.
Registration Authority (RA)Registration AuthorityThe front-end for identity verification for the CA; responsible for verifying the applicant's identity (e.g., domain ownership, organizational documents) and notifying the CA to issue the certificate upon approval. The CA itself does not interact directly with applicants.
End-Entity CertificateEnd-Entity CertificateThe certificate used by websites or services, issued by an Intermediate CA.
Certificate Revocation List (CRL)Certificate Revocation ListA periodically published list of revoked certificates; clients must actively download and check it.
Online Certificate Status Protocol (OCSP)Online Certificate Status ProtocolA protocol for real-time querying of the revocation status of a single certificate; more real-time than CRL.

Certificate Trust Chain and OCSP Stapling

  • Trust chain verification process: Browser receives server certificate → checks issuer (Intermediate CA) → traces back to Root CA → confirms Root CA is in the trust list.
  • OCSP Stapling: The server queries the CA for its own certificate status on behalf of the client and attaches the result to the TLS handshake, avoiding the need for the client to connect directly to the CA (reducing latency and privacy risks).
Diagram
C# Example: X.509 Certificate Loading and Verification
csharp
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

// --- Load PFX certificate (including private key) ---
string pfxPath = "server.pfx";
string pfxPassword = "P@ssw0rd";
using X509Certificate2 cert = new(pfxPath, pfxPassword, X509KeyStorageFlags.EphemeralKeySet);

Console.WriteLine($"Subject:    {cert.Subject}");
Console.WriteLine($"Issuer:     {cert.Issuer}");
Console.WriteLine($"Not Before: {cert.NotBefore:yyyy-MM-dd}");
Console.WriteLine($"Not After:  {cert.NotAfter:yyyy-MM-dd}");
Console.WriteLine($"Thumbprint: {cert.Thumbprint}");
Console.WriteLine($"Algorithm:  {cert.SignatureAlgorithm.FriendlyName}");
Console.WriteLine($"Has PK:     {cert.HasPrivateKey}");

// --- Verify Certificate Chain ---
using X509Chain chain = new();
chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;

bool isChainValid = chain.Build(cert);
Console.WriteLine($"<br />Certificate chain verification result: {isChainValid}");

foreach (X509ChainElement element in chain.ChainElements) {
    Console.WriteLine($"  [{element.Certificate.Subject}]");
    foreach (X509ChainStatus status in element.ChainElementStatus) {
        Console.WriteLine($"    Status: {status.StatusInformation}");
    }
}

// --- RSA Signing with Certificate ---
using RSA? rsaPrivateKey = cert.GetRSAPrivateKey();
if (rsaPrivateKey is not null) {
    byte[] data = Encoding.UTF8.GetBytes("Data to be signed");
    byte[] signature = rsaPrivateKey.SignData(
        data,
        HashAlgorithmName.SHA256,
        RSASignaturePadding.Pss
    );
    Console.WriteLine($"<br />RSA Signature: {Convert.ToBase64String(signature)}");

    using RSA? rsaPublicKey = cert.GetRSAPublicKey();
    bool verified = rsaPublicKey!.VerifyData(
        data,
        signature,
        HashAlgorithmName.SHA256,
        RSASignaturePadding.Pss
    );
    Console.WriteLine($"Signature verification: {verified}");
}

HSM (Hardware Security Module)

An HSM is a physical device specifically designed to protect cryptographic keys, providing a tamper-resistant security environment:

AspectDescription
Core FunctionKey generation, storage, and usage all occur within the hardware; private keys never leave the HSM.
Tamper-Resistant DesignAutomatically destroys keys (Zeroization) upon physical tampering.
Compliance StandardsFIPS 140-2 / FIPS 140-3 (US Federal Standard), divided into Levels 1–4.
Common UsesRoot CA key protection, banking transaction signing, TLS private key protection, code signing.
Cloud FormatsAWS CloudHSM, Azure Dedicated HSM, GCP Cloud HSM.

HSM and Key Protection

  • Difference between HSM and software key management (e.g., Azure Key Vault, AWS KMS): HSM guarantees that keys are computed within a FIPS-validated hardware boundary, whereas keys in software solutions may briefly appear in memory.
  • The Root CA private key for enterprise PKI is typically stored in an offline HSM (not connected to the network) and is only enabled when issuing Intermediate CA certificates.

Key Archiving and Escrow

MechanismEnglishDescriptionRisk
Key ArchivingKey ArchivingOrganization keeps copies of encryption keys to decrypt historical data in the future (e.g., reading encrypted files after an employee leaves).The archive storage itself becomes a target for attacks.
Key EscrowKey EscrowKey copies are held by a trusted third party (e.g., government agency or notary) and can be retrieved under specific conditions (e.g., court order).Third-party compromise or abuse of power leading to large-scale key leakage.
  • Key archiving is generally only applicable to encryption keys; signing keys should not be archived (otherwise, others could impersonate the signer).
  • Archived keys must be stored with high-strength encryption and strictly limited access permissions (e.g., multi-party control).

TLS (Transport Layer Security)

Version Evolution Comparison (SSL → TLS)

VersionRelease YearStatusKey Changes and Milestones
SSL 2.01995Deprecated (RFC 6176)First public version; severe design flaws: MAC uses fast hashes like MD5, handshake lacks integrity protection, vulnerable to replay attacks.
SSL 3.01996Deprecated (RFC 7568)Major fixes to SSL 2.0, but still vulnerable to POODLE (Padding Oracle On Downgraded Legacy Encryption) attacks, exploiting CBC (Cipher Block Chaining) padding flaws; overall design is unfixable.
TLS 1.01999Deprecated (RFC 8996)Redefined based on SSL 3.0, introduced HMAC (Hash-based Message Authentication Code) to replace MAC, but fixed IV (Initialization Vector) made BEAST (Browser Exploit Against SSL/TLS) attacks possible.
TLS 1.12006Deprecated (RFC 8996)Added Explicit IV to fix BEAST vulnerability; limited improvements, mainly a transitional version.
TLS 1.22008Widely deployed, still effectiveIntroduced AEAD (Authenticated Encryption with Associated Data) encryption mode (AES-GCM); replaced MD5/SHA-1 with fast hashes like SHA-256; supports ECDHE (Elliptic Curve Diffie-Hellman Ephemeral) for Perfect Forward Secrecy (PFS).
TLS 1.32018 (RFC 8446)Current StandardRemoved all weak algorithms (RSA static key exchange, RC4, DES, 3DES); key exchange forces ephemeral (EC)DHE, providing PFS; handshake reduced from 2-RTT (Round-Trip Time) to 1-RTT; supports 0-RTT fast reconnection.

TLS Version Evolution

  • SSL 2.0 / 3.0: Fundamental design flaws; completely deprecated and should not be used in any scenario.
  • TLS 1.0 / 1.1: Extended patches for SSL with limited progress; fully disabled by mainstream browsers in 2021.
  • TLS 1.2: A milestone for modern HTTPS, introducing AEAD + SHA-256 + ECDHE; still widely deployed. The SHA-256 here is used as a fast hash for handshake integrity and cryptographic operations like HMAC / PRF.
  • TLS 1.3: Eliminates all compromises for "backward compatibility"; key exchange forces ephemeral (EC)DHE, and the handshake is faster. The only exception is the PSK-only connection resumption mode, which does not provide PFS.

TLS 1.2 Handshake Process (ECDHE Key Exchange)

The purpose of the TLS handshake is to securely establish symmetric encryption keys over an insecure network. The following is the full process for TLS 1.2 using ECDHE key exchange:

StepDirectionActionTransmission StatePurpose
1Client → ServerClient HelloPlaintextInform supported Cipher Suites, TLS version, Client Random
2Server → ClientServer HelloPlaintextSelect cipher suite, return Server Random
3Server → ClientCertificatePlaintextPresent X.509 certificate (containing server public key) for client identity verification
4Server → ClientServer Key ExchangePlaintext (with signature)Send ECDHE ephemeral public key, signed with server's long-term private key to ensure parameters are not tampered with
5Client → ServerClient Key ExchangePlaintextSend client's ECDHE ephemeral public key
6Both sidesCalculate Pre-Master SecretNot sentBoth independently calculate the same value using the other's ECDHE public key + their own ECDHE private key
7Both sidesDerive Session KeyNot sentDerive symmetric encryption key using Client Random + Server Random + Pre-Master Secret
8Both sidesChange Cipher SpecPlaintextNotify the other party: subsequent messages will use symmetric encryption
9Both sidesFinishedEncryptedFirst encrypted message, verifying the integrity of the entire handshake process; verification is based on fast hash family cryptographic operations
10Both sidesApplication Data TransferSymmetric EncryptionAll subsequent data is encrypted and transmitted using the Session Key
Diagram

Key Design of TLS Handshake

  • Why not use asymmetric encryption directly for data? Asymmetric encryption is extremely slow (hundreds to thousands of times slower than symmetric) and is only used during the handshake phase to negotiate symmetric keys.
  • The E (Ephemeral) in ECDHE stands for "ephemeral key": A new key pair is generated for every connection. Even if the server's long-term private key is leaked in the future, past communications cannot be decrypted. This is Perfect Forward Secrecy (PFS).
  • The signature in Step 4 uses the server's long-term private key (corresponding to the public key in the certificate), not the ECDHE ephemeral private key. Before signing, parameters are first processed with a fast hash to allow the client to confirm that "these ECDHE parameters indeed came from the real server."
  • Simplification in TLS 1.3: Removes Change Cipher Spec, handshake reduced from 2-RTT to 1-RTT; supports 0-RTT fast reconnection (but carries a risk of replay attacks).

Improvements in TLS 1.3

AspectTLS 1.2TLS 1.3
Key ExchangeSupports RSA static key exchange (No PFS)Only allows ephemeral ECDHE / DHE, providing PFS
Handshake Latency2-RTT1-RTT (supports 0-RTT fast reconnection)
Cipher SuitesSupports legacy modes like CBC, RC4Only allows AEAD (AES-GCM, ChaCha20-Poly1305)
Hash AlgorithmSupports MD5, SHA-1Only allows fast hashes SHA-256 and above
Handshake EncryptionMost of the handshake is plaintextHandshake messages are encrypted after Server Hello
0-RTTNot supportedSupported (risk of replay attacks, use with caution)

Practical advice: New systems should default to TLS 1.3; if support for legacy clients is required, allow TLS 1.2 but must disable RSA key exchange and CBC mode.

Perfect Forward Secrecy (PFS)

PFS ensures that past encrypted communications remain secure even if the server's long-term private key is leaked:

Key Exchange MethodPFSDescription
RSA Static Key ExchangeClient encrypts Pre-Master Secret with server public key; once server private key is leaked, all historical traffic can be decrypted.
DHE / ECDHE (Ephemeral Key)A new ephemeral key pair is generated for each connection; the ephemeral private key is destroyed after the connection ends, making it impossible to retroactively decrypt even if the long-term private key is leaked.

TLS 1.3's standard full handshake forces the use of ephemeral (EC)DHE, providing PFS; PSK-only connection resumption and 0-RTT early data are not covered by this guarantee.

Diffie-Hellman Key Exchange and Man-in-the-Middle Attack Risk

Diffie-Hellman (DH) allows two parties to negotiate a shared secret over an insecure channel, but the original DH protocol does not provide identity verification, making it vulnerable to Man-in-the-Middle (MitM) attacks:

Diagram

Prevention: In TLS, DH/ECDHE parameters must be paired with the server's digital signature (parameters are first processed with a fast hash, then signed with the long-term private key) to allow the client to verify that the parameters indeed came from a legitimate server. This is the purpose of TLS handshake Step 4 (Server Key Exchange + Signature).

Cryptographic Attack Methods

Attack TypeEnglishDescriptionTarget
Birthday AttackBirthday AttackExploits the birthday paradox to find hash collisions within 2^(n/2) attempts (n is hash bit length). E.g., 128-bit hash only needs ~2^64 attempts.Hash functions (MD5, SHA-1)
Length Extension AttackLength Extension AttackFor Merkle–Damgård hash functions (MD5, SHA-1, SHA-2), an attacker holding the output of H(secret ‖ message) can calculate a new valid hash after appending extra content without knowing the secret. Often used to attack MACs implemented as "key directly prepended to message".Hash functions; MACs implemented as H(key ‖ message)
Known Plaintext AttackKnown Plaintext AttackAttacker possesses some "plaintext + corresponding ciphertext" pairs to derive the key or decrypt other ciphertexts.Symmetric encryption
Chosen Plaintext AttackChosen Plaintext AttackAttacker can choose arbitrary plaintext and obtain its ciphertext (e.g., accessing an encryption Oracle) to derive the key.Symmetric/Asymmetric encryption
Chosen Ciphertext AttackChosen Ciphertext AttackAttacker can choose ciphertext and obtain the decryption result to reverse-engineer the key. RSA without padding is particularly vulnerable.Asymmetric encryption
Side-Channel AttackSide-Channel AttackDerives keys through physical characteristics like execution time, power consumption, electromagnetic radiation, etc., rather than attacking the algorithm's math directly.All cryptographic implementations
Replay AttackReplay AttackIntercepts and resends valid encrypted messages (e.g., authentication tokens) to impersonate a legitimate user.Authentication protocols
Padding Oracle AttackPadding Oracle AttackExploits different server responses to padding errors to decrypt ciphertext byte-by-byte (e.g., POODLE, Lucky 13).CBC mode padding
Downgrade AttackDowngrade AttackForces both parties to use a weaker encryption version or algorithm (e.g., POODLE forcing a downgrade to SSL 3.0).Protocol negotiation

Prevention Focus

  • Birthday Attack: Use hash functions of 256 bits or more (SHA-256+), where collisions require 2^128 attempts.
  • Length Extension Attack: Use HMAC instead of H(key ‖ message); or switch to SHA-3 (Keccak sponge structure, naturally immune to this attack).
  • Side-Channel Attack: Use constant-time comparisons (e.g., CryptographicOperations.FixedTimeEquals) to avoid Timing Attacks.
  • Downgrade Attack: Disable all known insecure protocol versions and cipher suites.
Birthday Attack: Why is it called "Birthday"?

Birthday Paradox: In a room, you only need 23 people to have a >50% chance that two share the same birthday. Intuitively, this number is low (there are 365 days in a year), but the counter-intuitive key is: we are looking for any pair that matches, not "matching a specific person."

There are 23 × 22 ÷ 2 = 253 pairs to compare among 23 people, causing the probability to rise rapidly.

Attack TargetCostAnalogy
Pre-image Attack: Finding an input for a specific hash value2^n attemptsFinding someone who shares a birthday with a specific person
Collision Attack: Finding any two inputs with the same hash value2^(n/2) attemptsFinding any two people in the room who share a birthday

The cost of a collision attack is only "half the exponent" of a pre-image attack, so collision attacks must be considered when choosing hash lengths.

  • SHA-1 (160-bit): Collision theory requires 2^80 attempts; Google found a real collision in 2017 (SHAttered project), and SHA-1 is officially declared insecure.
  • SHA-256 (256-bit): Collision requires 2^128 attempts; currently uncrackable.
Padding Oracle Attack: How to decrypt ciphertext byte-by-byte?

CBC decryption formula: P_i = D(C_i) ⊕ C_{i-1}, where D is block decryption, C is ciphertext, and P is plaintext.

PKCS#7 Padding Rule: Plaintext must be padded to 16 bytes. If k bytes are missing, pad with k bytes, each with the value k.

Missing 1 byte  → pad 01
Missing 2 bytes → pad 02 02
Missing 3 bytes → pad 03 03 03

Attack Principle: The server verifies padding after decryption and returns a "padding error" if the format is invalid. This error response is the "Oracle" (a queryable black box). The attacker restores plaintext byte-by-byte:

  1. Take the last ciphertext block C_n and the preceding one C_{n-1}.
  2. Try modifying the last byte of C_{n-1} one by one (256 possibilities).
  3. When the server returns "padding correct," it means the last byte after decryption is exactly 0x01.
  4. Calculation: D(C_n)[last] = 0x01 ⊕ test_value, then reverse the real plaintext: P_n[last] = D(C_n)[last] ⊕ original C_{n-1}[last].
  5. Once the last byte is known, adjust the expected padding to 02 02, repeat the calculation for the second-to-last byte, until the entire block is restored.

Each byte takes at most 256 queries; 16 bytes in a block take at most 4,096 queries to decrypt an entire block. POODLE and Lucky 13 attacks fall into this category.

For a complete explanation of side-channel attacks (including timing attack byte-by-byte cases, law of large numbers, Spectre, and cloud co-residency), see Common Software Vulnerability Exploitation Table.

Downgrade Attack: How to fake "incompetence" to trick servers into using old protocols?

In the first step of the TLS handshake, the client sends a ClientHello, declaring the protocol versions and cipher suites it supports. The server selects the highest version supported by both.

Attack Process (using POODLE as an example):

  1. The attacker (Man-in-the-Middle) intercepts the client's ClientHello.
  2. The attacker tampers with the supported version list, changing it from TLS 1.3, 1.2, 1.1, 1.0, SSL 3.0 to only SSL 3.0.
  3. The server receives this and assumes the client only supports SSL 3.0, downgrading the negotiation according to specifications.
  4. SSL 3.0's CBC padding rule has the POODLE vulnerability, allowing the attacker to decrypt the traffic.

Why the attack is feasible: To maintain compatibility with legacy clients (old browsers, old devices), servers usually keep multiple versions enabled; as long as an old version is enabled, a downgrade target exists.

Defense:

  • Server-side: Explicitly disable all versions below TLS 1.1, leaving no room for legacy downgrades.
  • TLS 1.3: If a server supporting TLS 1.3 negotiates to TLS 1.2 or lower with a client, it must write a Downgrade Sentinel in the last 8 bytes of ServerHello.Random; the client detects this and aborts the handshake to prevent downgrade attacks.

Common Cryptographic Tool Command Examples

Common OpenSSL Commands
bash
# --- Generate RSA private key (2048-bit) ---
openssl genpkey -algorithm RSA -out private.pem -pkeyopt rsa_keygen_bits:2048

# --- Export public key from private key ---
openssl pkey -in private.pem -pubout -out public.pem

# --- Generate ECDSA private key (P-256 curve) ---
openssl genpkey -algorithm EC -out ec-private.pem -pkeyopt ec_paramgen_curve:P-256

# --- Generate self-signed certificate (valid for 365 days) ---
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes \
  -subj "/C=TW/ST=Taipei/L=Taipei/O=MyOrg/CN=localhost"

# --- View certificate content ---
openssl x509 -in cert.pem -text -noout

# --- View remote server certificate chain ---
openssl s_client -connect www.google.com:443 -showcerts </dev/null 2>/dev/null | \
  openssl x509 -text -noout

# --- Verify certificate ---
openssl verify -CAfile ca-bundle.pem cert.pem

# --- AES-256-CBC encrypt file (using PBKDF2 to derive key) ---
openssl enc -aes-256-cbc -salt -pbkdf2 -in plain.txt -out encrypted.bin

# --- AES-256-CBC decrypt file ---
openssl enc -aes-256-cbc -d -pbkdf2 -in encrypted.bin -out decrypted.txt

# --- Calculate SHA-256 hash ---
openssl dgst -sha256 file.txt

# --- HMAC-SHA256 ---
openssl dgst -sha256 -hmac "my-secret-key" file.txt
Common GPG Commands
bash
# --- Generate key pair ---
gpg --full-generate-key

# --- List keys ---
gpg --list-keys
gpg --list-secret-keys

# --- Symmetric encryption (AES-256, password protected) ---
gpg --symmetric --cipher-algo AES256 -o encrypted.gpg plain.txt

# --- Symmetric decryption ---
gpg --decrypt -o decrypted.txt encrypted.gpg

# --- Asymmetric encryption (using recipient's public key) ---
gpg --encrypt --recipient [email protected] -o encrypted.gpg plain.txt

# --- Asymmetric decryption ---
gpg --decrypt -o decrypted.txt encrypted.gpg

# --- Digital signature ---
gpg --sign --armor -o signed.asc document.txt

# --- Verify signature ---
gpg --verify signed.asc

# --- Export public key ---
gpg --export --armor [email protected] > public.asc

# --- Import public key ---
gpg --import public.asc

Post-Quantum Cryptography (PQC) and Key Encapsulation Mechanism (KEM)

Post-Quantum Cryptography (PQC) refers to encryption algorithms designed to withstand threats from quantum computers, aiming to replace traditional asymmetric encryption that relies on the "integer factorization problem" (RSA) or "discrete logarithm problem" (ECC, DH). Shor's Algorithm can crack these problems with periodic algebraic structures in polynomial time on quantum computers; PQC uses mathematical foundations that quantum computers cannot accelerate as its security basis.

NIST PQC Standardization Results (Official standard in 2024):

AlgorithmDescriptionTypeMathematical FoundationStandard
CRYSTALS-Kyber (ML-KEM)Module-Lattice Key Encapsulation MechanismKey Encapsulation (KEM)LatticeFIPS 203
CRYSTALS-Dilithium (ML-DSA)Module-Lattice Digital Signature AlgorithmDigital SignatureLatticeFIPS 204
SPHINCS+ (SLH-DSA)Stateless Hash-based Digital Signature AlgorithmDigital SignatureHash FunctionFIPS 205

Why Lattice-based problems provide post-quantum security

The security of Lattice-based Cryptography is built on high-dimensional geometric problems like Learning With Errors (LWE).

Intuitive understanding of LWE: You are given a large number of linear equations with tiny random errors (b = A·s + e mod q, where A and b are known, s is the hidden secret vector, and e is the random error). Can you reverse-engineer s?

  • No error (e = 0): Solving linear equations, solvable with high school math.
  • With random error (e ≠ 0): The problem becomes exponentially difficult; there are no known efficient algorithms for either traditional or quantum computers.

Shor's Algorithm uses Quantum Fourier Transform (QFT) to accelerate problems with periodic algebraic structures; the random error in LWE destroys this regularity, rendering quantum acceleration ineffective.

Key Encapsulation Mechanism (KEM):

KEM is the mechanism used in the post-quantum era to securely transmit symmetric keys, functionally equivalent to a "post-quantum digital envelope":

  1. The receiver generates a KEM public/private key pair.
  2. The sender performs encapsulation using the receiver's public key, generating: a ciphertext and a shared secret.
  3. The receiver performs decapsulation using the private key to recover the same shared secret.
  4. Both parties communicate using symmetric encryption with the shared secret.

"Harvest Now, Decrypt Later" Attack

Attackers collect and store encrypted transmitted data now, to decrypt it after quantum computers mature. Even if quantum computers are not yet practical, data with long-term confidentiality requirements (e.g., government secrets, medical records) needs to start migrating to PQC algorithms now.

Quantum Threat to Symmetric Encryption: Grover's Algorithm

Grover's Algorithm primarily threatens symmetric encryption systems; it provides a quadratic acceleration for brute-force attacks, effectively halving the secure key length:

AlgorithmTraditional Security StrengthEffective Strength after Quantum ComputerConclusion
AES-128128 bits64 bits❌ Insufficient, not recommended for long-term protection
AES-256256 bits128 bits✅ Currently considered sufficient, NIST recommended

Symmetric encryption does not need to be replaced by PQC algorithms; increasing the key length to 256 bits is sufficient to counter Grover's Algorithm.

Quantum Key Distribution (QKD)

Quantum Key Distribution (QKD) uses the principles of quantum mechanics to securely exchange encryption keys between two parties. Any eavesdropping attempt will disturb the quantum state, allowing the receiver to detect it.

Operating Principle (using the BB84 protocol as an example):

  1. The sender randomly transmits a sequence of photons in four polarization states (↕, ↔, ↗, ↘).
  2. The receiver randomly chooses a basis (+ or ×) to measure each photon.
  3. Both parties compare the bases used over a public channel and keep the quantum bits where the "bases match" as raw key material.
  4. If an eavesdropper measures the photons during transmission, according to the Heisenberg Uncertainty Principle and the No-cloning Theorem, the act of measurement itself changes the quantum state, causing the receiver to detect an abnormal bit error rate, leading both parties to discard the key.

Positioning Differences between QKD and PQC:

QKDPQC
Security BasisLaws of quantum physics (No-cloning theorem)Mathematical problems (Lattice, Hash functions)
Deployment NeedsRequires dedicated quantum channels (fiber or satellite), high hardware costSoftware algorithm replacement, runs on existing network infrastructure
Resistance TargetAny eavesdropping (even quantum computers cannot steal keys without leaving a trace)Primarily against quantum computer-based cracking (Shor's Algorithm)
MaturityShort-distance commercial (tens to hundreds of km), long-distance relies on relays or satellitesNIST announced first batch of standards in 2024, rapid progress toward practical use
Main LimitationsExpensive equipment, distance limited, infrastructure hard to scaleCorrectness of algorithms still under continuous verification
  • QKD solves "whether the key exchange process is eavesdropped"; PQC solves "whether encryption can still resist cracking after computing power increases." The two goals are complementary, not mutually exclusive.
  • "Harvest Now, Decrypt Later" attacks can be prevented by QKD (eavesdropping is detected at the time), but QKD's high deployment threshold makes PQC a more realistic short-term transition plan.

Homomorphic Encryption

Homomorphic encryption allows mathematical operations to be performed directly on ciphertext; the decrypted result is equivalent to the result of performing the operation on the plaintext first, without ever needing to decrypt the original data.

Intuitively, ciphertext looks like a string of meaningless gibberish (like Base64 or Hex), and it is hard to imagine "doing math" on it. The key is that the design goals of the two types of encryption are different:

Traditional Encryption (AES / RSA)Homomorphic Encryption
Design GoalDeliberately destroys algebraic structure, making ciphertext and plaintext completely unrelatedDeliberately preserves specific algebraic structure, making operations on ciphertext correspond to operations on plaintext
Ciphertext OperationDoing math on ciphertext results in meaningless output after decryptionDoing addition or multiplication on ciphertext results in the correct plaintext operation result after decryption
CostHigh performance, widely usedComplex design, extremely low performance while maintaining semantic security

Modern FHE schemes (BFV, BGV, CKKS, etc.) are built on Ring-LWE lattice problems; ciphertext is essentially high-dimensional vectors/polynomials, and their algebraic structure naturally supports the propagation of addition and multiplication. This also gives FHE post-quantum security.

TypeEnglishSupported OperationsDescription
Partial Homomorphic (PHE)Partial Homomorphic EncryptionAddition only OR Multiplication onlyEasier to implement; RSA multiplication homomorphism falls into this category
Somewhat Homomorphic (SHE)Somewhat Homomorphic EncryptionAddition + Limited MultiplicationDecryption fails after exceeding the operation limit due to error accumulation
Fully Homomorphic (FHE)Fully Homomorphic EncryptionAddition + Multiplication (unlimited)Theoretically supports arbitrary computation, but computational overhead is extremely high
  • Typical Applications: Cloud machine learning (cloud providers train or infer models without accessing raw personal data), joint analysis of medical data across institutions (institutions analyze together without sharing raw data).
  • Current Status of FHE: Computational overhead is far higher than plaintext computation (currently thousands to tens of thousands of times slower), still in the research and limited application stage.
  • Different purpose from PQC: PQC solves "how to make encryption resist quantum computer cracking"; homomorphic encryption solves "how to use encrypted data without decrypting it."

Network Attacks

ARP Spoofing

ARP (Address Resolution Protocol) is responsible for resolving IP addresses to MAC addresses. Within a local area network (LAN), when a computer needs to send data to another device (such as a gateway router), it only knows the target's IP address, but actual network transmission requires a MAC address. ARP functions by broadcasting a query within the local network: "What is the MAC address for IP 192.168.1.1?" Once the target replies, a connection can be established between the two.

The ARP protocol includes a legitimate proactive notification mechanism called Gratuitous ARP: a device can broadcast its own IP/MAC mapping without waiting for a query. This is common during startup, network card replacement, or VRRP/HSRP master-slave failover, allowing all devices on the network segment to quickly update their ARP caches. Since ARP lacks a verification mechanism, devices receiving these unsolicited broadcasts update their caches directly without verifying if the source is legitimate. ARP Spoofing abuses this mechanism: an attacker continuously sends forged Gratuitous ARP packets, causing the victim and the gateway to update each other's MAC addresses to the attacker's MAC, thereby achieving a Man-in-the-Middle (MITM) attack.

Diagram

Attack Impact:

  • Man-in-the-Middle attack: Eavesdropping on or tampering with unencrypted traffic.
  • DoS: Dropping intercepted traffic, causing the victim's network to disconnect.
  • Session hijacking: Intercepting authenticated Session Tokens.

Defense Measures:

Defense MechanismEnglishDescription
Dynamic ARP InspectionDAIThe switch validates ARP packets and only allows legitimate IP/MAC mappings
Static ARPStatic ARP EntryManually configure ARP mappings for critical devices to prevent overwriting
802.1X AuthenticationPort-based NACControls the identity of devices entering the network segment, reducing unauthorized devices
Encrypted TransmissionHTTPS / TLS / IPsecEven if traffic is intercepted, the plaintext content cannot be read

L3 Network Layer Attacks

BGP Hijacking

BGP (Border Gateway Protocol) is the core routing protocol of the Internet, responsible for exchanging routing information between ISPs (such as Chunghwa Telecom, Hinet) and large network operators to determine "the fastest path for packets." While general enterprise internal networks do not use it directly, the entire Internet's cross-border traffic forwarding relies on it.

BGP Hijacking occurs when an attacker maliciously announces IP prefixes that do not belong to them, causing the global routing system to direct traffic to systems controlled by the attacker. The root cause of many global network outages in history (such as the Facebook outage in 2021) was incorrect BGP routing rule configurations or malicious manipulation.

Why the attack is effective: Longest Prefix Match

When a BGP router looks up a destination, it follows the "Longest Prefix Match" principle. The prefix length is the number of fixed bits in the IP address, counting from the left. The more fixed bits there are, the smaller the address range that can be matched, and the router considers it a more precise destination.

Taking the packet destination 203.0.113.50 as an example, first convert it to binary:

203      .  0       . 113      . 50
11001011 . 00000000 . 01110001 . 00110010

There are two rules in the routing table, differing only in the 1st bit of the last octet:

/24: First 24 bits fixed (first three groups), last 8 bits arbitrary
11001011 . 00000000 . 01110001 . ????????
→ 203.0.113.0 ~ 203.0.113.255, total 256 addresses

/25: First 25 bits fixed (first three groups + 1st bit of the fourth group), last 7 bits arbitrary
11001011 . 00000000 . 01110001 . 0???????
→ The 25th bit must be 0, others arbitrary
→ 203.0.113.0 ~ 203.0.113.127, total 128 addresses

The last group of 203.0.113.50 is 00110010, and the 25th bit is 0, which matches both rules. However, /25 has one more fixed bit and a narrower range, so the router prioritizes it. An attacker only needs to announce a longer prefix than the legitimate holder to make the router send traffic to them.

Diagram

Since BGP itself does not verify whether the announcer actually owns the IP range, other ASes will directly trust this routing information and update their routing tables.

Normal Routing vs. Post-Hijacking Comparison:

Diagram

Attack Techniques:

  • The attacker controls an AS and announces a sub-prefix of the target IP range to BGP neighbors (e.g., if the original holder announces /24, the attacker announces a more precise /25), causing routers to prioritize directing traffic to the attacker.
  • Can be used for eavesdropping, traffic analysis, Man-in-the-Middle attacks (selective traffic forwarding), or DoS (dropping traffic directly).

Defense Measures:

Defense MechanismEnglishDescription
Route Origin ValidationRPKIUses PKI certificates to verify if an AS is authorized to announce a specific IP prefix
BGP Security ExtensionBGPsecAdds digital signatures to BGP route announcements to verify route path integrity
Prefix FilteringPrefix FilteringFilters illegitimate route announcements at the ISP boundary
Anomaly DetectionBGP MonitoringMonitors abnormal changes in the routing table to detect hijacking events in time

L6-L7 Application Layer Attacks

SSL Stripping

The vulnerability of SSL Stripping does not lie in the server, but in the fact that when a user enters bank.com, they do not proactively add https://, and the browser sends an HTTP request first for compatibility. The attacker intercepts this "first HTTP request." The server only establishes an HTTPS connection with the attacker and has no idea that someone is intervening in the middle.

Prerequisite: Obtaining a Man-in-the-Middle position

TechniqueDescription
ARP SpoofingForging ARP responses on the same network segment so the victim's packets are sent to the attacker first
Malicious Wi-Fi HotspotSetting up an open hotspot (e.g., "Free_Airport_WiFi"); once connected, the attacker acts as the gateway

Attack Flow

The attacker uses tools like sslstrip as a transparent proxy, pretending to be a normal client to the server and a normal server to the victim:

Diagram

The webpage appearance seen by the victim is identical; the only difference is the absence of the lock icon in the address bar. The server side also functions normally throughout, with no way to detect the attack.

Defense

HSTS forces the browser to upgrade http:// to https:// internally before the packet is sent, so the attacker can never intercept the first plaintext request.

NBT-NS / LLMNR Poisoning

When Windows resolves hostnames, if a DNS query fails, it will sequentially attempt LLMNR (Link-Local Multicast Name Resolution) and NBT-NS (NetBIOS Name Service) broadcasts, asking all devices on the local network: "Who is 'fileserver'?"

Neither of these broadcast protocols has a verification mechanism. An attacker can impersonate the target host and respond, causing the victim to proactively initiate NTLM authentication with the attacker, from which the attacker captures the NTLM hash. A common attack tool is Responder.

Diagram

Attack Impact:

  • After capturing the NTLM Hash, passwords can be cracked offline.
  • Directly perform NTLM Relay attacks to access other internal network resources as the victim, without needing to crack the password.
  • A common technique for ransomware lateral movement within enterprise networks.

Defense Measures:

Defense MeasureDescription
Disable LLMNRDisable via GPO (Computer Configuration → Windows Settings → Name Resolution Policy)
Disable NBT-NSDisable NetBIOS over TCP/IP in network adapter settings
Enable SMB SigningPrevents NTLM Relay attacks; even if the Hash is captured, it cannot be relayed
Strong Password PolicyReduces the probability of NTLM Hash being cracked by brute force

DNS Spoofing and Cache Poisoning

DNS is responsible for resolving domain names (e.g., bank.com) to IP addresses. If an attacker can make the victim receive a forged DNS response, they can direct traffic to a malicious server, even if the URL entered by the user is completely correct.

Difference between the two attacks

AttackEnglishTargetPrerequisiteScope of Impact
DNS SpoofingDNS SpoofingSingle userRequires MITM position (e.g., ARP Spoofing)Victim's local machine only
DNS Cache PoisoningDNS Cache PoisoningDNS resolver's cacheDoes not need to be on-path, can be launched remotelyAll users using that resolver

DNS Cache Poisoning Principle

DNS queries use UDP. An attacker can send a large number of forged response packets before the real response arrives. As long as the Transaction ID (16-bit random number) in the forged response is guessed correctly, the resolver will accept and cache it. In 2008, Dan Kaminsky discovered that combining source port guessing could significantly increase the success rate (Kaminsky Attack), prompting improvements to the DNS protocol and the widespread promotion of DNSSEC.

Defense Measures

Defense MeasureDescription
DNSSECAdds digital signatures to DNS responses so resolvers can verify that the response has not been tampered with (see DNS Security)
Randomized Source PortIncreases the randomness that the attacker needs to guess, making Cache Poisoning more difficult
DoH / DoTEncrypts DNS queries to prevent on-path attackers from tampering with responses

L3-L7 Denial of Service Attacks (DoS / DDoS)

Attack CategorySpecific Attack TechniqueOSI LayerCore Principle and Behavioral Characteristics
Volumetric Attacks
Goal: Saturate bandwidth
UDP FloodL4 TransportSends massive amounts of meaningless UDP packets to random ports, simply using brute force to saturate network bandwidth.
DNS AmplificationL3/L4Forges victim's IP to query DNS, using UDP characteristics to "reflect" and saturate the victim with response traffic tens of times larger. Amplification factor is about 28–54x.
NTP AmplificationL3/L4Same principle as DNS amplification, but uses the NTP monlist command vulnerability; amplification factor can reach 500–700x.
Memcached AmplificationL3/L4Uses insecure default settings of Memcached (UDP port 11211); amplification factor can be as high as 10,000–50,000x, currently the highest known reflection amplification protocol.
Protocol Attacks
Goal: Exhaust device connections
SYN Flood (Handshake attack)L4 TransportExploits TCP three-way handshake vulnerability by sending only SYN requests without completing the final confirmation, exhausting the server's connection state table.
Ping of DeathL3 NetworkSends malformed ICMP packets exceeding the maximum length allowed by the IP protocol, causing memory overflow or crashes on the receiving end.
SSL/TLS ExhaustionL6/L7Continuously initiates HTTPS handshakes, exploiting the fact that "server decryption is extremely CPU-intensive" to paralyze server computing power.
Application Layer Attacks
Goal: Exhaust system resources
HTTP Flood (CC attack; CC = Challenge Collapsar)L7 ApplicationSimulates real users, continuously sending complete HTTP requests at extremely high speeds (e.g., constantly refreshing pages or querying databases), overwhelming server CPU/memory with request volume.
SlowlorisL7 ApplicationAlso HTTP requests, but deliberately slows down transmission speed and never finishes, keeping connections open indefinitely until the HTTP connection pool is full. Relies on holding without releasing, not volume.
Connection Pool ExhaustionL7 ApplicationSimultaneously issues concurrent requests exceeding the database connection pool limit, each triggering slow queries or long transactions, keeping all slots occupied during the query period. Legitimate requests receive "wait for connection timeout" errors. No database credentials required; can be launched via Web interface.
DNS FloodL7 ApplicationSends massive random resolution requests to the target domain's DNS server, making it unable to serve normal users.

Amplification and Reflection DDoS

  • Amplification attacks are usually also reflection attacks: forging the source IP and borrowing third-party servers (like DNS/NTP/Memcached) to direct large amounts of traffic to the victim.
  • Amplification factor comparison: DNS ≈ 28–54x < NTP ≈ 500–700x < Memcached ≈ 10,000–50,000x (highest).
  • Volumetric attacks focus on bps (bits per second, saturating bandwidth); protocol/application layer attacks focus on pps (packets per second) or rps (requests per second).

Differences between three application layer attacks

HTTP Flood, Slowloris, and Connection Pool Exhaustion all belong to application layer DoS, but they target different resources and use different techniques:

AttackTarget ResourceTechnique
HTTP FloodCPU / Memory (General)Massive complete requests, overwhelming by volume
SlowlorisHTTP Connection PoolFew requests deliberately not finished, connections never released ("borrow without returning")
Connection Pool ExhaustionDatabase Connection PoolTriggers slow queries, keeping slots occupied during the query period ("borrowing all at once")

The three can be combined: a large number of HTTP Flood requests may also exhaust the database connection pool.

Connection Pool defaults and costs: The default Max Pool Size for ADO.NET is 100, per connection string (different connection strings have independent pools). When the limit is set too high, each SQL Server connection consumes server-side memory (starting at about 24 KB) and a Worker Thread. Excessive connections lead to increased memory pressure, thread exhaustion, and increased CPU context switching overhead, causing overall throughput to drop.

Defense core: Use Rate Limiting at the Web layer to block abnormal concurrency, rather than simply increasing the connection pool limit. The higher the limit, the more resources the attacker can occupy.

Volumetric attack flow (using DNS amplification as an example)

For an amplification attack to succeed, two conditions must be met simultaneously:

  1. Response is far larger than the request: The attacker only needs to send small packets, but can cause third-party servers to generate response traffic tens or even tens of thousands of times larger. DNS ANY queries can return all records (about 50x); NTP monlist command returns a list of the 600 most recent connection hosts (about 500–700x); Memcached spits out the entire cache data, up to 50,000x.
  2. Source IP can be forged: UDP has no handshake, and the server does not verify the source IP; upon receiving the packet, it directly sends the response back to the address indicated by the "Source IP." The attacker fills in the victim's IP as the source IP, and the third-party server sends all the massive responses to the victim. The attacker does not appear in the final traffic at all. Because TCP has a three-way handshake, if the source IP is forged, the handshake cannot be completed, so amplification techniques can only use UDP.

The victim receives a large number of DNS/NTP responses they never requested, but these packets come from legitimate servers, making it difficult to directly identify them as an attack at the traffic level.

Diagram

Protocol attack flow (SYN Flood)

SYN Flood exploits the design of the TCP three-way handshake: after the server receives a SYN, it must reserve resources while waiting for the subsequent ACK. The attacker sends a large number of SYNs but never completes the handshake, exhausting the server's half-open connection table.

Diagram

DDoS Upstream Mitigation: BGP Flowspec (RFC 5575)

Traditional DDoS mitigation relies on Scrubbing Centers or CDN Anycast to absorb traffic, meaning attack traffic must still reach the enterprise boundary before being filtered. BGP Flowspec goes a step further, allowing enterprises to broadcast traffic filtering rules to upstream ISP backbone routers via the BGP protocol, so that malicious traffic is dropped before it enters the enterprise network.

AspectDescription
PrincipleExtends traditional BGP capabilities by carrying filtering rules (NLRI) in BGP Update messages, including conditions such as source IP, destination port, protocol, packet length, etc., which upstream routers automatically apply upon receipt.
Trigger MethodAfter an enterprise detects a DDoS attack, it dynamically announces Flowspec rules; once the attack stops, the rules are withdrawn without affecting normal routing.
Protection ScopeCan precisely filter based on attack characteristics (e.g., source IP range, UDP port 53 amplification attack), which is more granular than whole-range IP Blackhole Routing.
LimitationsRequires ISP and equipment support for RFC 5575; rule broadcasting has propagation delay (BGP convergence time); incorrect rules may affect normal traffic.

BGP Flowspec vs Blackhole Routing (RTBH)

  • Blackhole Routing (RTBH, Remotely Triggered Black Hole): Drops all traffic to the target IP, stopping the attack but also preventing legitimate users from connecting to that IP.
  • BGP Flowspec: Can precisely filter based on a five-tuple (source/destination IP, source/destination port, protocol), dropping only traffic matching attack characteristics while allowing legitimate traffic to pass; the cost is that rules are more complex and require ISP support.

Attack Techniques

Malware and Attack Chains

Malware Type Comparison Table

TypeIndependent Survival (Need host?)Propagation and Trigger MethodMain Purpose and CharacteristicsTypical Example / Notes
VirusNo (must attach to normal files)Requires user to click or execute host fileDamage system, infect other filesMacro virus, CIH
WormYes (independent executable)Proactively scans network vulnerabilities, self-replicates and spreadsConsumes network bandwidth and system resourcesBlaster, SQL Slammer
TrojanYes (disguised as normal software)Deceives user into downloading and installingSteal secrets, open backdoors for remote controlBanking Trojan, Remote Access Trojan (RAT)
RansomwareYesVia phishing emails, vulnerabilities, or Trojan implantationEncrypts and locks files, demands ransom for decryptionWannaCry (has worm propagation characteristics), LockBit
SpywareYesBundled with free software or malicious webpagesKeylogging, monitoring browsing behavior, stealing passwordsKeylogger
Logic BombNo (usually implanted in normal programs)Triggers only when specific conditions are met (e.g., specific date, specific operation)Insider retaliation, timed destructionMalicious database deletion script

OFAC Sanctions List Verification Obligation Before Ransomware Payment

OFAC (Office of Foreign Assets Control, U.S. Department of the Treasury) maintains a sanctions list (SDN List) that specifies countries, organizations, and individuals sanctioned by the United States.

For enterprises with headquarters or operations within the United States (or involving USD transactions):

  • If a decision is made to pay a ransom, you must first verify whether the attacker/payee is on the OFAC sanctions list.
  • Providing funds to sanctioned hostile hacker organizations or terrorists is a serious federal felony, which may result in huge fines or even criminal prosecution, regardless of whether you were aware (strict liability).
  • Even if they are not on the sanctions list, it is recommended to proactively report to OFAC after payment (voluntary disclosure can mitigate liability).

Confirming whether the target is on the list is not the primary goal: Enterprises do not pay to avoid becoming a source of funds for sanctioned entities, rather than to ensure the attacker can definitely decrypt, as the latter falls under negotiation and technical assessment.

Virus Advanced Variant Technology Comparison

  • Polymorphic Virus: Changes its own encrypted signature every time it infects, but the decrypted malicious core code remains the same. The goal is to evade signature-based scanning by traditional antivirus software.
  • Metamorphic Virus: Rewrites its own code every time it infects (e.g., replacing instructions, inserting garbage code), making the appearance and structure completely different, but the malicious behavior performed is the same. This is the most difficult type to detect.

Packing & Obfuscation Technology

Static analysis by antivirus software scans files on the hard drive and compares them against signatures of known malicious programs. Packing makes the appearance on the hard drive completely different from the real code, thereby bypassing scanning:

Packing Flow:

  1. Packer compresses/encrypts the original malicious code and merges it with a Stub program into a new executable.
  2. When antivirus scans, it sees compressed garbled code + Stub, finds no malicious signature → allows it.
  3. When the user executes, the Stub runs first, decompresses/decrypts the original code, and loads it into memory.
  4. The malicious code only appears and executes in memory.
TechnologyOperation MethodAttacker GoalCommon Tools/Techniques
PackingOriginal code compressed/encrypted and wrapped in Stub, decompressed by Stub at runtimeMakes the static appearance on the hard drive different from the real code, bypassing signature scanningUPX (general compression), Themida (commercial-grade protection), custom Packer
ObfuscationRewrites code structure (e.g., scrambling execution flow, inserting garbage code), execution result remains the sameIncreases time cost for reverse engineering and manual analysisVariable renaming, Control Flow Flattening, garbage code insertion
CrypterAdvanced form of packing, protects Payload with high-strength encryption, dynamically decrypts at runtimeAchieves FUD (Fully Undetectable), signature of generated file is different every timeCustom Crypter

How to detect packing: Packed executables show three anomalies on the hard drive: content looks like garbled code (loses regularity after compression/encryption), readable text like error messages and API names expected in normal programs disappears, and the list of Windows function calls is extremely simplified (Stub only needs a few APIs to load the real program into memory, other calls appear after decompression).

Countermeasures: Sandbox dynamic analysis (let it run and observe behavior), Memory Dump (take a memory snapshot after decompression for analysis), behavior detection instead of signature comparison.

Cyber Kill Chain Comparison Table

The Cyber Kill Chain proposed by Lockheed Martin breaks down APT (Advanced Persistent Threat) attacks into 7 stages:

StageEnglishChineseDescriptionTypical Activities
1Reconnaissance偵察Collect target informationOSINT, social media investigation, scanning public services
2Weaponization武器化Create attack toolsCombine vulnerability exploits with Payload into deliverable weapons (e.g., malicious PDF)
3Delivery遞送Deliver weapon to targetPhishing emails, malicious websites, USB drops
4Exploitation利用Trigger vulnerabilityExploit software vulnerabilities, zero-day attacks, user clicks malicious attachments
5Installation安裝Implant persistent backdoorInstall RAT, create scheduled tasks, modify registry keys
6Command & Control (C2)指揮與控制Establish remote control channelConnect back to C2 server, receive commands
7Actions on Objectives目標行動Achieve final goalData theft, data destruction, lateral movement, ransomware

Cyber Kill Chain vs MITRE ATT&CK

Comparison AspectCyber Kill ChainMITRE ATT&CK
StructureLinear 7-stage chainTactics × Techniques matrix
GranularityHigh-level attack flowFine-grained techniques and sub-techniques
ScenarioUnderstanding overall attack flow, post-incident backtrackingThreat detection rule writing, red/blue team exercises
MaintenanceProposed by Lockheed Martin, updated less frequentlyContinuously updated by MITRE, community contributions
  • Kill Chain defense mindset: Interrupting the attack chain at any stage can stop the attack; the earlier the interruption, the lower the cost.
  • ATT&CK defense mindset: Build detection rules for each technique to increase the attacker's cost and exposure risk.
  • The two are complementary: Use Kill Chain to understand the full picture of the attack, use ATT&CK to build fine-grained detection capabilities.
  • Vulnerability exploit techniques corresponding to Kill Chain stages: Exploitation stage often sees Buffer Overflow, ROP (Return-Oriented Programming); Installation stage often sees DLL Side-Loading.
Diagram

Parentheses contain official MITRE ATT&CK Tactic IDs, which can be queried at attack.mitre.org for all specific techniques under that tactic.

Kill Chain StageCorresponding ATT&CK TacticNote
ReconnaissanceReconnaissance (TA0043)One-to-one correspondence, collecting target information.
WeaponizationResource Development (TA0042)Acquiring or building attack infrastructure and tools.
DeliveryInitial Access (TA0001)Phishing, vulnerability exploitation, supply chain attacks, etc.
ExploitationExecution (TA0002), Defense Evasion (TA0005)Executing code after triggering vulnerability and evading detection.
InstallationPersistence (TA0003), Privilege Escalation (TA0004)Implanting backdoors and escalating privileges to maintain access.
C2Command and Control (TA0011)Establishing remote control channels.
Actions on ObjectivesCollection (TA0009), Exfiltration (TA0010), Impact (TA0040)Collecting, exfiltrating data, or causing damage.

MITRE Defense-side Frameworks:

In addition to ATT&CK (attacker perspective), MITRE has two defense-side frameworks:

FrameworkPositioningDescription
MITRE D3FENDEncyclopedia for defendersOrganizes defense techniques in a knowledge graph and maps them precisely to ATT&CK attack techniques. Each D3FEND technique indicates which ATT&CK TTPs it can defend against; content covers five defense actions: Harden, Detect, Isolate, Deceive, Evict.
MITRE ENGAGEActive defense and adversarial engagementFocuses on network deception and adversarial engagement, guiding defenders on how to use active measures like decoys (Honeypot / Honey Token) and misleading information to expose attacker TTPs, consume attack resources, and collect threat intelligence.

Distinction between the three

  • ATT&CK: Describes "how the attacker hits," for red teams to design attack chains and blue teams to build detection rules.
  • D3FEND: Describes "how the defender blocks," the defense-side mapping of ATT&CK.
  • ENGAGE: Describes "how the defender lures and counters," emphasizing actively inducing attackers into observable environments.

Web and API Attacks

Cross-Site Scripting (XSS) Comparison Table

TypeMalicious Script Storage LocationTrigger ConditionScope of ImpactCore Defense Focus
Reflected XSSURL parameters (not stored on server)Tricked into clicking a link containing a malicious payloadSingle user who clicks the linkValidate and filter HTTP request parameters
Stored XSSDatabase or file system (permanently stored on server)Any user views the infected page (e.g., message boards, forums)All users viewing the page (highest damage potential)Output encoding, filter input content
DOM-based XSSFrontend browser DOM environment (server is completely unaware)Triggered when frontend JavaScript reads malicious sources and dynamically modifies the DOMSingle user who triggers the DOM operationAvoid high-risk JS APIs like innerHTML

Common Confusion: XSS / CSRF / SSRF

The three have similar names but completely different attack targets and mechanisms:

Comparison AspectXSS (Cross-Site Scripting)CSRF (Cross-Site Request Forgery)SSRF (Server-Side Request Forgery)
Attack TargetUser's browserUser's authenticated sessionThe server itself
Core MechanismInject malicious scripts into web pages to execute in the user's browserUse the user's browser-saved cookies to forge requests to the target siteInduce the server to send requests to internal or external resources
PrerequisitesSite does not correctly filter/encode outputUser is logged into the target site and the session is validServer accepts a user-provided URL and makes a request
Attacker CapabilitiesSteal cookies/sessions, page defacement, keyloggingPerform actions as the victim (e.g., transfer funds, change passwords)Access internal services (e.g., cloud metadata API 169.254.169.254), port scanning
Main DefenseOutput Encoding, CSP, HttpOnly CookieAnti-CSRF Token, SameSite Cookie, Referer validationWhitelist URLs/IPs, block private IP ranges, do not return full responses
OWASP CategoryA05 InjectionA01 Broken Access ControlA01 Broken Access Control (formerly 2021 A10 SSRF)
  • XSS attacks the user's browser (client-side); CSRF borrows the user's authentication status to perform actions; SSRF attacks the server-side.
  • CSRF does not require injecting any scripts; it only requires the user to visit a malicious page while logged in.
  • In practice, XSS and CSRF are often used together: injecting a script via XSS that automatically sends a CSRF request.
C# XSS Defense: Output Encoding and Input Validation

Incorrect Example: Embedding user input directly into HTML

csharp
// ❌ Dangerous: Direct concatenation of user input; attacker can inject <script>alert('XSS')</script>
app.MapGet("/greet", (string name) =>
    Results.Content($"<h1>Hello, {name}</h1>", "text/html"));

Correct Approach: Use HtmlEncoder for Output Encoding

csharp
using System.Text.Encodings.Web;

app.MapGet("/greet", (string name) => {
    string safeName = HtmlEncoder.Default.Encode(name);
    return Results.Content($"<h1>Hello, {safeName}</h1>", "text/html");
});
// Input <script>alert('XSS')</script>
// Output &lt;script&gt;alert(&#x27;XSS&#x27;)&lt;/script&gt; (displayed as plain text in browser)

ASP.NET Core Razor Automatic Encoding

When using the @ syntax to output variables in Razor views, HTML encoding is performed automatically by default:

csharp
// @Model.Name is automatically encoded in Razor, which is safe
<p>@Model.Name</p>

// ❌ Dangerous: @Html.Raw() bypasses automatic encoding; disable unless content is confirmed safe
<p>@Html.Raw(Model.Name)</p>

CSP (Content Security Policy) Header Configuration

csharp
// Add CSP header in Middleware to restrict script sources
app.Use(async (context, next) => {
    context.Response.Headers.Append(
        "Content-Security-Policy",
        "default-src 'self'; script-src 'self'; style-src 'self'"
    );
    await next();
});
C# CSRF Token Validation Concept

ASP.NET Core has a built-in Anti-Forgery Token mechanism that defends against CSRF using the double-submit cookie pattern:

MVC Controller

csharp
// Form automatically generates hidden field __RequestVerificationToken
// Razor View:
// <form asp-action="Transfer" method="post">
//     @Html.AntiForgeryToken()
//     ...
// </form>

[HttpPost]
[ValidateAntiForgeryToken] // Validates Token; returns 400 if mismatch
public IActionResult Transfer(TransferRequest request) {
    // Execute transfer logic
    return RedirectToAction("Success");
}

Minimal API / SPA Scenarios (Manual Token Retrieval)

csharp
using Microsoft.AspNetCore.Antiforgery;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddAntiforgery(options => {
    options.HeaderName = "X-XSRF-TOKEN"; // SPA sends Token back via this Header
});

WebApplication app = builder.Build();

app.MapGet("/antiforgery/token", (IAntiforgery antiforgery, HttpContext context) => {
    AntiforgeryTokenSet tokens = antiforgery.GetAndStoreTokens(context);
    // Write Request Token to Cookie; frontend JavaScript reads it and puts it in the Header
    context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken!,
        new CookieOptions { HttpOnly = false, SameSite = SameSiteMode.Strict });
    return Results.Ok();
});

app.MapPost("/api/transfer", async (IAntiforgery antiforgery, HttpContext context) => {
    await antiforgery.ValidateRequestAsync(context); // Throws AntiforgeryValidationException on failure
    // Execute business logic
    return Results.Ok();
});
  • Principle: The server generates a random token and embeds it in a hidden form field or cookie. Upon submission, the server compares the cookie token with the form/header token. An attacker's cross-site request cannot read the target site's cookie content (Same-Origin Policy), so they cannot provide the correct token.
  • Combined with SameSite=Strict or SameSite=Lax cookie attributes, this further prevents the browser from automatically attaching cookies to cross-site requests.

OWASP (Open Web Application Security Project) Top 10 2025 Comparison Table

OWASP Top 10:2025 is the official ranking of the most common security risks for web applications.

RankCategoryKey Description
A01Broken Access ControlUsers can access unauthorized functions or data (e.g., manually changing URLs to access others' data). 2025 incorporates SSRF-related controls from the former A10 into this category.
A02Security MisconfigurationUpgraded to second place from A05 in 2021. Includes unchanged default credentials, unnecessary enabled features/services, incorrect permission settings, etc.
A03Software Supply Chain FailuresExpanded and renamed in 2025, extending from 2021's A06 Vulnerable and Outdated Components. Scope covers the entire supply chain: dependencies, CI/CD, package source trust, and third-party services.
A04Cryptographic FailuresDropped from A02 in 2021. Covers insufficient transport encryption, weak hashing, and improper key management.
A05InjectionDropped from A03 in 2021. Includes SQL Injection, OS Command Injection, LDAP (Lightweight Directory Access Protocol) Injection, etc.
A06Insecure DesignEmphasizes architectural flaws during the design phase rather than implementation vulnerabilities, indicating that security must be integrated early in the SDLC (Software Development Life Cycle).
A07Authentication FailuresShortened from "Identification and Authentication Failures" in 2021 to "Authentication Failures" in 2025.
A08Software or Data Integrity FailuresFormerly "Software and Data Integrity Failures" in 2021; includes CI/CD (Continuous Integration/Continuous Delivery) supply chain attacks and unverified update mechanisms (e.g., hijacked plugin auto-updates).
A09Security Logging and Alerting FailuresFormerly "Logging and Monitoring" in 2021; changed to "Logging and Alerting" in 2025, emphasizing proactive alerting over passive monitoring.
A10Mishandling of Exceptional ConditionsNew in 2025. Improper error handling, boundary conditions, or unexpected state handling that may leak information or trigger unauthorized actions.

Major Changes in the 2025 Version (vs 2021)

  • New: A10 Mishandling of Exceptional Conditions.
  • Expanded and Renamed: A06 Vulnerable and Outdated Components → A03 Software Supply Chain Failures; scope expanded from "using outdated components" to the entire software supply chain.
  • No Longer Independent: 2021's A10 Server-Side Request Forgery (SSRF) controls are now merged into A01 Broken Access Control.
  • Rank Changes: Security Misconfiguration (A05→A02), Cryptographic Failures (A02→A04), Injection (A03→A05).
  • Fine-tuning: A07 removed "Identification and", A09 changed "Monitoring" to "Alerting", A08 changed "and" to "or".

Common Confusion: SQL Injection / Command Injection

Comparison AspectSQL InjectionCommand Injection (OS Command Injection)
Injection TargetSQL database query statementsOperating system shell commands
Attack VectorSQL fragments embedded in form fields, URL parameters, or HTTP headersParameters concatenated into shell calls like cmd.exe /c or /bin/sh -c
HarmData leakage, data tampering, authentication bypass, or even executing system commands via xp_cmdshellExecuting arbitrary commands directly with server privileges (RCE)
Root CauseString concatenation of SQL instead of using parameterized queriesPassing user input directly into shell execution
Main DefenseParameterized Query, ORM, least-privileged database accountsAvoid calling shells; use whitelist validation for input when necessary; do not concatenate command strings
  • SQL Injection variants: Blind SQL Injection (no direct output, inferred via boolean conditions or time delays), Second-Order SQL Injection (malicious input is stored first and triggered in subsequent queries).
  • High-risk APIs for Command Injection in C#: Process.Start() combined with cmd /c or /bin/sh -c, where parameters originate from user input.

Supply Chain Attack

Corresponds to OWASP A03 (Software Supply Chain Failures, expanded from 2021 A06 Vulnerable and Outdated Components) and A08 (Software or Data Integrity Failures). Attackers do not attack the target directly but infiltrate its upstream dependencies.

Real-world Cases

CaseYearMethodImpact
SolarWinds (SUNBURST)2020Attacker compromised SolarWinds' build server, planting a backdoor in Orion software updatesUS government agencies and thousands of enterprises affected
Codecov2021Bash Uploader script tampered with to steal environment variables and keys in CI/CD environmentsOpen source projects and enterprise CI environments using Codecov
Log4Shell (CVE-2021-44228)2021RCE vulnerability in Apache Log4j 2's JNDI Lookup featureHundreds of millions of Java applications worldwide affected
event-stream (npm)2018After package ownership transfer, new maintainer injected malicious code to steal cryptocurrency walletsnpm package with millions of downloads
3CX2023Supply chain attack chain: compromised upstream vendor Trading Technologies, then infected 3CX desktop appsHundreds of thousands of enterprise users

Prevention Measures

  • Use SCA (Software Composition Analysis) tools to scan for dependency vulnerabilities (e.g., dotnet list package --vulnerable, Snyk, OWASP Dependency-Check).

  • Integrate package integrity verification into the CI/CD pipeline (e.g., NuGet signature verification, npm package-lock.json hash comparison).

  • Adopt SBOM (Software Bill of Materials) to track all dependency versions.

  • Establish internal package mirror repositories (e.g., Artifactory, Azure Artifacts) to avoid pulling directly from public registries.

  • Principle of Least Privilege: CI/CD environment secrets should only be authorized for necessary pipeline stages.

  • SRI (Subresource Integrity): When referencing external CDN JavaScript libraries or CSS, add the integrity="sha384-..." attribute to <script> / <link> tags (hash values are pre-calculated by the developer and hardcoded). The browser recalculates the hash after downloading; if it does not match, execution is refused, preventing tampered CDN resources (e.g., if a vendor is compromised or a man-in-the-middle injects a crypto-miner) from being loaded.

    html
    <script src="https://cdn.example.com/jquery.min.js"
            integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
            crossorigin="anonymous"></script>

BOLA / IDOR (API Security)

BOLA (Broken Object Level Authorization) is the #1 risk in the OWASP API Security Top 10 and is the specific manifestation of OWASP Top 10 A01 (Broken Access Control) in API scenarios.

IDOR (Insecure Direct Object Reference) is the most common form of BOLA:

  • Example: A user retrieves their own order via GET /api/orders/1001, then changes 1001 to 1002 to access someone else's order.
  • Root cause: The backend only verifies if the user is logged in, but fails to verify if the user has permission to access the specific resource.

Defense measures:

  • Backend must enforce a check for every request: "Is this user the owner of this resource?"
  • Use unpredictable resource identifiers (e.g., UUIDs) instead of auto-incrementing IDs (reduces guessability, but is not a complete solution).
  • Implement access control policies at the API Gateway layer.

API Security (OWASP API Security Top 10)

The OWASP API Security Top 10 (2023 version) lists the most common security risks for APIs:

RankRisk NameDescription
API1Broken Object Level Authorization (BOLA)Failure to verify if a user has permission to access a specific object (e.g., modifying the ID in /api/users/123 to access others' data)
API2Broken AuthenticationFlaws in authentication mechanisms (weak tokens, missing rate limiting, tokens not expiring)
API3Broken Object Property Level AuthorizationReturning too many properties or allowing modification of properties that should not be modified (Mass Assignment)
API4Unrestricted Resource ConsumptionFailure to limit API request frequency, response size, or batch quantities, which can be exploited for DoS attacks
API5Broken Function Level AuthorizationFailure to verify if a user has permission to call a specific API endpoint (e.g., a regular user accessing an admin API)
API6Unrestricted Access to Sensitive Business FlowsLack of protection mechanisms for sensitive business processes (e.g., bulk purchasing, ticket grabbing)
API7Server Side Request Forgery (SSRF)API accepts URL parameters and makes server-side requests, which can be exploited to access internal services
API8Security MisconfigurationMissing security headers, excessive error message disclosure, unnecessary enabled HTTP methods
API9Improper Inventory ManagementFailure to track all API versions and endpoints; old APIs not decommissioned become attack entry points
API10Unsafe Consumption of APIsTrusting data returned by third-party APIs without verification, potentially introducing malicious content
  • BOLA (API1) is the most common API vulnerability, fundamentally caused by a lack of object-level authorization checks.
  • Difference between API Security and Web Application Security: APIs usually lack a UI, and attackers interact directly with HTTP requests; traditional WAF rules (targeting HTML/Forms) may not provide effective protection.
  • Defense Recommendations: API Gateway combined with Rate Limiting, OAuth 2.0 + JWT, input validation, and the principle of least return (only return necessary fields).

Unique Security Issues of GraphQL APIs

REST APIs usually map each endpoint to a specific resource, making them easy for attackers to enumerate; GraphQL has a single endpoint but a built-in Introspection Query mechanism, which allows querying the complete schema structure by default:

graphql
{ __schema { types { name fields { name } } } }

During the reconnaissance phase of a penetration test, an attacker can execute an Introspection Query to obtain all available queries, mutations, type definitions, and field names, effectively generating an automated API attack surface list and significantly shortening the time required to explore BOLA/injection vulnerabilities.

Defense:

  • Disable Introspection in production environments (enable only in development).
  • Even if Introspection is disabled, implement field-level access control to prevent unauthorized access to sensitive fields.
  • Enable query complexity limits (Query Depth Limiting / Cost Analysis) to prevent DoS caused by recursive queries.

OWASP Cloud-Native Application Security Top 10 Comparison Table

OWASP Cloud-Native Application Security (CNAS) is an OWASP project focused on cloud-native applications (containers, Kubernetes, Serverless, and cloud services). Its official GitHub Repository was archived in 2025, and no official final version has been released. The table below summarizes the ten risks frequently cited in the project's drafts, which can serve as a checklist for cloud-native security.

RankCategoryKey Description
CNAS-1Insecure ConfigurationCloud, container, or orchestration misconfigurations, including fragile IaC (Infrastructure as Code) and publicly exposed storage.
CNAS-2Injection FlawsMalicious input targeting traditional applications, APIs, or cloud services.
CNAS-3Improper Authentication & AuthorizationWeak authentication and overly permissive IAM roles, allowing unauthorized access to services and APIs.
CNAS-4Supply Chain VulnerabilitiesUnprotected CI/CD pipelines, contaminated container images, and insecure registry communication.
CNAS-5Insecure Secrets ManagementHardcoded or leaked credentials, tokens, and encryption keys.
CNAS-6Insecure Network PoliciesInsufficient network segmentation, allowing unauthorized lateral movement.
CNAS-7Vulnerable ComponentsUsing outdated libraries and open-source packages with known CVEs.
CNAS-8Improper Asset ManagementFailure to track ephemeral cloud resources, leading to Shadow IT.
CNAS-9Inadequate Resource QuotasLack of resource usage limits, creating risks of DoS and skyrocketing cloud costs.
CNAS-10Ineffective Logging & MonitoringLack of real-time visibility, hindering incident detection.

Common Software Vulnerability Exploitation Table

TechniqueCategoryPrincipleCountermeasures
Buffer OverflowMemory SafetyWriting data beyond buffer boundaries, overwriting adjacent memory (including return addresses) to control the execution flow.Boundary checking, Stack Canary, ASLR, DEP/NX.
Use-After-Free (UAF)Memory SafetyA pointer is not cleared after memory is freed; an attacker allocates a new object to occupy the same address and manipulates the new object via the old pointer.Set pointers to null after free, use Smart Pointers, memory-safe languages (e.g., Rust).
Heap SprayMemory SafetyFilling the heap with large amounts of malicious Shellcode and NOP Sleds to increase the probability of jumping to malicious code; often used with UAF or overflows.ASLR, limiting heap memory allocation, memory isolation.
Integer OverflowMemory SafetyInteger operations wrap around after exceeding the type range, leading to incorrect length calculations, which can trigger buffer overflows or logic bypasses.Use safe integer libraries, check ranges before explicit type casting; C# defaults to unchecked (silent wrap), use checked blocks or /checked compiler options to throw OverflowException.
Format String AttackInjectionPassing user input directly into formatting functions like printf() (e.g., printf(user_input)), allowing attackers to read Stack memory or write to arbitrary addresses using %n.Never use external input as a format string; always use printf("%s", user_input); enable compiler warnings.
XML External Entity (XXE)InjectionThe XML parser processes external entity declarations (e.g., <!ENTITY xxe SYSTEM "file:///etc/passwd">), allowing local file reading or SSRF requests.Disable external entity parsing (FEATURE_EXTERNAL_GENERAL_ENTITIES = false), use parsers that do not support DTDs.
Server-Side Template Injection (SSTI)InjectionUser input is embedded into template engines (e.g., Jinja2, Thymeleaf) and rendered directly, triggering template syntax to execute arbitrary code (RCE).Never concatenate input into template strings; sandbox template engines; separate data from template context.
Insecure DeserializationInjectionWhen deserializing untrusted data, attackers manipulate the Object Graph to trigger specific constructors or callbacks (e.g., PHP's __wakeup, C#'s IDeserializationCallback), leading to RCE or privilege escalation. C#'s BinaryFormatter is a classic high-risk API (marked obsolete in .NET 5, removed in .NET 9).Do not deserialize data from untrusted sources; in C#, use System.Text.Json or XmlSerializer with type whitelisting; verify signatures of serialized data.
Race Condition / TOCTOU (Time-of-Check to Time-of-Use)Logic & RaceA time gap exists between the "check" and the "use"; attackers replace resources (e.g., files, symbolic links) during this window, invalidating the check.Use atomic operations; lock resources immediately after acquisition; avoid relying on intermediate states that can be modified externally.
Prototype PollutionLogic & RaceIn JavaScript, manipulating __proto__ or constructor.prototype to pollute the prototype shared by all objects, injecting malicious properties that affect global behavior.Create objects without prototypes using Object.create(null); freeze prototypes (Object.freeze(Object.prototype)); filter input keys (e.g., __proto__, constructor).
Side-channel AttackObservationInstead of attacking the algorithm directly, physical characteristics (timing, power consumption, electromagnetic radiation, cache hit rates) are measured during execution to recover sensitive data. Classic case: Spectre / Meltdown exploits CPU Speculative Execution cache timing differences to read cross-process memory.Constant-time algorithms, Retpoline/IBRS, KPTI.
Zero-day ExploitOtherExploiting unknown vulnerabilities that are not yet public or patched; since no patch exists, defenders cannot rely on signature-based detection.Defense in Depth; behavioral detection (EDR / XDR); Principle of Least Privilege; network segmentation to limit lateral movement.
Fileless MalwareOtherMalicious code does not reside on disk, executing directly in memory (e.g., via PowerShell, WMI, Living-off-the-Land Binaries). Traditional antivirus relies on file scanning, making it difficult to detect.AMSI (Antimalware Scan Interface): Script engines (PowerShell, VBScript, WMI) pass content to the AV engine before execution, intercepting decrypted plaintext scripts in memory—the most effective system-level defense against LOLBins; Script Block Logging; behavioral EDR; restrict PowerShell execution policies.
Return-Oriented Programming (ROP)Memory SafetySince DEP/NX prevents Shellcode execution, attackers chain existing program Gadgets (short code sequences ending in ret) to construct arbitrary logic, bypassing non-executable restrictions.CFI, Shadow Stack, ASLR make Gadget addresses hard to predict and control flow impossible to hijack.
DLL Side-LoadingSupply Chain / HijackingExploiting the Windows DLL search order by placing a malicious DLL with the same name in the legitimate program's directory, causing the program to load the malicious version first. Often paired with legitimate, digitally signed programs (e.g., antivirus) to evade detection.Enable SafeDllSearchMode (default); use absolute paths to load DLLs in code; verify DLL digital signatures; implement application whitelisting.
Buffer Overflow: Stack Memory Layout

When a function is called, the Stack grows from high addresses to low addresses. The full layout with Stack Canary defense is as follows:

High Address
┌──────────────────────────────────┐
│  Return Address                  │  ← Attack Target: Overwrite to control execution flow
├──────────────────────────────────┤
│  Saved EBP (Caller Base Pointer) │  ← Overwritten as a side effect
├──────────────────────────────────┤
│  ★ Stack Canary                  │  ← Defense: Random value, verified before return
├──────────────────────────────────┤
│  Local Variables / Buffer        │  ← Starting point of write, overflow direction ↑
└──────────────────────────────────┘
Low Address (Stack grows downward)

State after overflow:

High Address
┌──────────────────────────────────┐
│  0xdeadbeef (Attacker Controlled)│  ← Return address has been tampered with!
├──────────────────────────────────┤
│  AAAAAAAA                        │  ← Saved EBP corrupted
├──────────────────────────────────┤
│  AAAAAAAA                        │  ← ★ Canary overwritten → Anomaly detected!
├──────────────────────────────────┤
│  AAAA... (Long input)            │  ← Buffer + Overflow
└──────────────────────────────────┘
Low Address

Normal vs. Overflow Comparison

Stack Position (High → Low)Normal StateAfter Overflow
Return Address0x00401234 (Legitimate)0xdeadbeef (Attacker Controlled)
Saved EBPCaller Base PointerAAAAAAAA (Corrupted)
Stack Canary0x7f3a9c01 (Random)AAAAAAAA (Overwritten → Detected!)
Buffer (16 bytes)Normal DataAAAA... (Long input)

Before the function ret instruction executes, the program verifies if the Canary is intact. If overwritten → the process is terminated immediately (__stack_chk_fail), preventing the attacker from controlling the return address.

The C# Case

C# code managed by the CLR has automatic boundary checking, so traditional Buffer Overflows cannot occur. However, when using unsafe blocks to manipulate raw pointers, boundary checking is bypassed:

csharp
unsafe void Vulnerable(string input) {
    byte* buffer = stackalloc byte[16];
    fixed (char* p = input) {
        for (int i = 0; i < input.Length; i++)
            buffer[i] = (byte)p[i]; // Overwrites Stack if input > 16 chars!
    }
}

Avoid using unsafe; for high-performance buffer operations, use Span<T> or Memory<T> (which still have boundary checking).

TOCTOU: The Time Gap Between Check and Use
Diagram

Root cause: The check (①) and use (③) are not atomic operations, leaving a exploitable time window in between.

C# Example

csharp
// Vulnerable: Time gap between File.Exists and File.WriteAllText
if (File.Exists(path)) {
    // Attacker might replace the symlink at 'path' here
    File.WriteAllText(path, data);
}

// Safer: FileMode.CreateNew provides atomic "create only if not exists" at the kernel level
// Throws IOException if it already exists (including symlink targets)
using FileStream fs = new(path, FileMode.CreateNew, FileAccess.Write);
using StreamWriter writer = new(fs);
writer.Write(data);

Note: In Unix environments, you should also use the O_NOFOLLOW flag (via P/Invoke in C#) to refuse following symbolic links; Windows symbolic links require administrator privileges, making the risk relatively lower.

Side-channel Attack: Why does "Observation" work?

Core premise: Algorithms exhibit subtle behavioral differences when processing different data, and these differences leak through measurable physical characteristics.

Example 1 — Timing Attack: Character Comparison

Common incorrect password comparison (C#):

csharp
// Vulnerable: Early return leaks timing information
bool ComparePassword(byte[] stored, byte[] input) {
    if (stored.Length != input.Length) {
        return false;
    }
    for (int i = 0; i < stored.Length; i++) {
        if (stored[i] != input[i]) {
            return false; // Returns early on first mismatch
        }
    }
    return true;
}
  • Input "bXXX" vs correct password "abcd": First character mismatch, returns immediately → shortest time.
  • Input "aXXX": First character matches, continues to second character before returning → slightly longer time.

Attackers can brute-force character by character: the input that takes the longest time indicates the correct character. No need to guess the whole string at once.

Why network latency doesn't stop the attack: Law of Large Numbers

Network latency is random noise (normal distribution, fluctuating randomly); CPU execution time difference is a fixed bias (due to the "number of matching bytes" factor). Attackers send 10,000 to 100,000 requests to the same target and take the average. With a large enough sample size, random latency cancels out, and the fixed underlying time difference emerges from the noise. This is feasible even over the public internet; it just requires enough samples.

The correct approach is to use constant-time comparison. .NET includes CryptographicOperations.FixedTimeEquals (.NET Core 2.1+):

csharp
using System.Security.Cryptography;

bool ComparePasswordSafe(byte[] stored, byte[] input) {
    // Execution time is constant regardless of how many characters match, leaking no info
    return CryptographicOperations.FixedTimeEquals(stored, input);
}

Example 2 — Cache Timing Attack: Spectre

To improve performance, CPUs perform "Speculative Execution" of subsequent instructions before conditional judgment results are available:

// Even if x is out of bounds, the CPU may speculatively execute:
if (x < array.length) {
    y = secret_array[x];           // ① Read secret data into y
    temp = probe_array[y * 4096];  // ② Access different cache lines based on y
}
// Speculation incorrect → results discarded, but cache state remains!

The attacker then times every position in probe_array:

  • Fast access (Cache Hit) → that cache line was accessed by ② → value of y can be deduced → secret_array[x] can be recovered.

This allows reading cross-process memory (including OS Kernel data) that the program theoretically has no access to.

Example 3 — Cloud Co-residency Attack

The "resource sharing pool" nature of cloud providers (AWS, GCP, Azure) allows multiple tenants to share the same physical server. An attacker can rent a VM for a few dollars and potentially be scheduled on the same physical machine as the target server, sharing the L3 Cache and memory bus.

The attacker then performs a cache timing attack locally, completely bypassing network latency noise, observing cache access patterns with nanosecond precision to calculate keys or sensitive data. Spectre and Meltdown are particularly dangerous in cloud environments precisely because the combination of "shared hardware + speculative execution" provides ideal attack conditions.

Countermeasure Principles

DefenseTargeted Leakage ChannelDescription
Constant-time AlgorithmsTiming differencesEnsures all inputs take the same amount of time to process, eliminating the timing signal at the root. Preferred solution for cryptographic operations (e.g., CryptographicOperations.FixedTimeEquals).
Jitter / Timing NoiseTiming differencesAdds random wait times before/after cryptographic operations, requiring attackers to collect more samples to isolate the signal. A secondary defense layer; cannot replace constant-time algorithms but increases attack cost; limited effectiveness against local side-channel attacks (nanosecond scale).
Retpoline / IBRSSpectre branch speculation
KPTI (Kernel Page-Table Isolation)Meltdown Kernel cache leakage
BinaryFormatter Deserialization RCE Example (C#)

BinaryFormatter reconstructs the full object graph during deserialization and triggers callbacks like IDeserializationCallback.OnDeserialization(). This is a simplified illustration; actual exploitation tools (like ysoserial.net) use built-in .NET Framework classes to chain a Gadget Chain, requiring no custom classes on the server side.

csharp
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

// Attacker: Create malicious object and serialize to bytes
BinaryFormatter formatter = new();
using MemoryStream ms = new();
formatter.Serialize(ms, new Payload());
byte[] maliciousBytes = ms.ToArray(); // Send these bytes to the victim

// Victim: Call Deserialize directly on external input (Dangerous!)
ms.Position = 0;
formatter.Deserialize(ms); // Triggers OnDeserialization

[Serializable]
class Payload : IDeserializationCallback {
    public void OnDeserialization(object? sender) =>
        Process.Start("calc.exe"); // Executes automatically after deserialization
}

Attack path in Web Forms era: ViewState is serialized and sent to the Client. If MAC validation is disabled or MachineKey is leaked, attackers can submit malicious ViewState → server deserializes → triggers Gadget Chain.

Clarification of Common Techniques

  • Side-channel Attack: Does not attack the algorithm itself, but observes physical characteristics like timing, power, and cache during execution. Spectre/Meltdown are cache timing leaks from CPU speculative execution.
  • Zero-day vs Fileless: Zero-day means "vulnerability not public"; Fileless means "attack does not touch disk." Both can exist simultaneously.
  • For principles and applicable attack techniques of general defense technologies (ASLR, DEP/NX, Stack Canary, CFI, etc.), see Common Security Defense Techniques Table.

Social Engineering and Identity Spoofing Attacks

Social Engineering Attack Types Table

TypeChinese NameTarget ScopeTechnique Characteristics
PhishingPhishingLarge, non-specific usersMass-sending phishing emails or pages impersonating well-known institutions (banks, Google).
Spear PhishingSpear PhishingSpecific individuals or organizationsPre-collecting target data to create highly personalized fake emails, making them difficult to identify.
WhalingWhalingHigh-level executives (CEO/CFO)A subset of Spear Phishing targeting individuals who can authorize large transfers or reveal secrets.
VishingVoice PhishingPhone usersImpersonating customer service or government agencies, requesting account info or verification codes over the phone.
SmishingSMS PhishingMobile usersSending malicious links via SMS, often disguised as package or prize notifications.
PretextingPretextingSpecific targetsFabricating a reasonable scenario (e.g., claiming to be IT support for remote assistance) to trick targets into providing info or performing actions.
BaitingBaitingNon-specific targetsExploiting human curiosity by leaving USB drives infected with malware in public places.

Social Engineering Classification Logic

  • Breadth decreases: Phishing → Spear Phishing → Whaling (targets shrink, precision increases).
  • Medium distinction:
    • Email = Phishing / Spear Phishing / Whaling
    • Phone = Vishing
    • SMS = Smishing
    • Physical Bait = Baiting

Password Attack Types Table

Attack TypeEnglishDescriptionSpeed vs. Stealth
Brute ForceBrute ForceTrying all possible password combinations for a single account (e.g., a, b, ..., aa, ab, ...)Slowest, most likely to trigger account lockout
Dictionary AttackDictionary AttackTrying passwords one by one from a pre-compiled list of common passwords (e.g., rockyou.txt)Faster than brute force, but limited by dictionary quality
Credential StuffingCredential StuffingUsing leaked account/password pairs (from other data breaches) to attempt mass logins on a target siteExploits password reuse habits; success rate approx. 0.1%–2%
Password SprayingPassword SprayingTrying a few common passwords (e.g., P@ssw0rd, Company2024!) against a large number of accountsOnly 1–2 attempts per account, deliberately avoiding lockout thresholds
Rainbow Table AttackRainbow Table AttackPre-calculating hashes for a large number of passwords into a lookup table to reverse-lookup target hashesSpace-time tradeoff; Salting renders rainbow tables ineffective

Credential Stuffing vs Password Spraying vs Brute Force

  • Brute Force: One account × all passwords → triggers lockout easily.
  • Password Spraying: All accounts × few passwords → low-frequency probing, avoids lockout.
  • Credential Stuffing: Known credential pairs × multiple sites → exploits password reuse.
  • Common defenses: MFA (FIDO2), anomalous login detection, Rate Limiting.
  • Defense differences: Brute Force is stopped by account lockout; Password Spraying requires global login failure trend analysis; Credential Stuffing requires detecting low-frequency attempts from many different source IPs.
Hydra / Medusa Brute Force Command Examples

Hydra and Medusa are open-source network login brute-force tools supporting multiple protocols.

Hydra Example

bash
# SSH Brute Force (Single user + password dictionary)
hydra -l admin -P /usr/share/wordlists/rockyou.txt ssh://192.168.1.100

# HTTP POST Form Brute Force
# /login is path, user=^USER^&pass=^PASS^ are parameters, "Invalid" is failure keyword
hydra -l admin -P passwords.txt 192.168.1.100 http-post-form \
  "/login:user=^USER^&pass=^PASS^:Invalid"

# Password Spraying (Multiple users + few passwords)
hydra -L users.txt -p 'Company2024!' ssh://192.168.1.100

# FTP Brute Force (User list + password list)
hydra -L users.txt -P passwords.txt ftp://192.168.1.100

# Limit concurrency and wait time (to avoid lockout or detection)
hydra -l admin -P passwords.txt -t 4 -W 3 ssh://192.168.1.100

Medusa Example

bash
# SSH Brute Force (Syntax similar to Hydra)
medusa -h 192.168.1.100 -u admin -P passwords.txt -M ssh

# Multi-host batch testing
medusa -H hosts.txt -U users.txt -P passwords.txt -M ssh
  • -l/-u: Single username; -L/-U: Username list file.
  • -p/-P: Single password / password list file.
  • -t: Hydra concurrency threads (default 16); -W: Wait seconds between attempts.
  • Use only in authorized penetration testing environments.

Watering Hole Attack

Attackers do not attack the target directly but instead compromise a website the target frequently visits, planting malicious code (e.g., browser exploits) and waiting for the target to visit.

  • Origin of name: Derived from lions waiting for prey at a watering hole.
  • Characteristics: An indirect attack combining Reconnaissance (identifying frequently visited sites) and Exploitation (browser/plugin vulnerabilities).
  • Typical scenario: Attacker compromises an industry forum or vendor site, plants JavaScript exploit code, and targets visitors from a specific industry.
  • Relationship to Drive-by Download: The technical means of a watering hole attack is usually a Drive-by Download.

Drive-by Download

Users simply browse a webpage (no clicking or downloading required), and vulnerabilities in the browser or its plugins are automatically exploited, silently installing malware in the background.

  • No user interaction required: Unlike phishing, users do not need to click links or confirm dialogs.
  • Common targets: Browsers, Flash Player (deprecated), Java Applets (deprecated), PDF Reader plugins.
  • Defense: Keep browsers and plugins updated, remove unnecessary plugins, enable browser sandboxing, deploy Web gateway filtering.

Typosquatting

Registering domain names similar to well-known domains, exploiting user typing errors to redirect traffic to malicious sites.

Spoofing TechniqueExample (Target: example.com)
Missing one characterexamle.com
Extra characterexamplle.com
Adjacent key swapezample.com (z and x are adjacent)
Homophone/Visual confusionexamp1e.com (digit 1 replaces letter l)
TLD replacementexample.org, example.co
  • Package Typosquatting: Uploading malicious packages with names similar to popular packages on platforms like npm or PyPI (e.g., coIors spoofing colors), a form of supply chain attack.
  • Defense: DNS monitoring, registering common typos as protection, using browser bookmarks for important sites, enabling lock files and hash verification for package management.

Business Email Compromise (BEC)

Attackers compromise or spoof corporate executive/partner email accounts to trick employees into transferring funds, leaking sensitive data, or changing payment information.

  • Difference from Whaling: Whaling is "phishing" an executive; BEC is "impersonating" an executive to email subordinates.
  • Common techniques:
    • CEO Fraud: Impersonating the CEO to email finance departments requesting urgent transfers.
    • Vendor Invoice Fraud: Impersonating vendors to notify of changed bank accounts.
    • Account Compromise: Directly compromising employee mailboxes to send fraudulent emails from real accounts (harder to detect).
  • Defense: Secondary verification via phone or in-person for large transfers, enabling email authentication (SPF, DKIM, DMARC), security awareness training.

IoT and Embedded System Attacks

IoT Attack Types Table

Chinese NameEnglish NameCore BehaviorCharacteristics & Identification
Black Hole AttackBlack Hole AttackMalicious node claims to be the best route but discards all packets passing throughTraffic enters and disappears; no response; like a "black hole"
Wormhole AttackWormhole AttackTwo malicious nodes establish a covert tunnel in the network, making remote nodes believe they are neighborsDistorts routing topology, interferes with routing protocols, difficult to detect
Sinkhole AttackSinkhole AttackMalicious node broadcasts fake "best routes," attracting large amounts of traffic before discarding or tamperingSimilar to Black Hole, but "attracts" first, affecting a wider range
Evil Twin AttackEvil Twin AttackSets up a fake hotspot with the same SSID as a legitimate AP, tricking devices into connectingCommon attack on wireless and IoT devices; can perform MITM or credential theft

Routing Attack Comparison

  • Black Hole = Absorbs packets and discards them, simplest.
  • Sinkhole = Absorbs packets and selectively processes them, attacker has more control.
  • Wormhole = Does not discard packets but distorts routing topology, making two remote malicious nodes look like neighbors, more stealthy.

Zigbee / IoT Protocol Security

ProtocolMain ApplicationKnown Risks
ZigbeeSmart home sensors, lighting, industrial sensorsKeys transmitted in plaintext over the air during initial network joining; many vendors use industry-known default keys, effectively public
BLE (Bluetooth Low Energy)Wearables, medical devices, smart locksOld pairing processes (BLE 4.0/4.1) susceptible to passive eavesdropping; KNOB attack can force encryption down to very low strength
Z-WaveDoor locks, blinds, appliance controlOld security framework (S0) uses fixed keys, susceptible to replay or cracking; new version (S2) improved, but old devices cannot be updated

Common Attack Techniques:

  • Key Sniffing: Intercepting keys transmitted over the air during initial device pairing.
  • Replay Attack: Recording legitimate control packets (e.g., "unlock" command) and re-sending them later to trigger the same action.
  • Firmware Downgrade Attack: Forcing devices to install older firmware to revert to a state with known vulnerabilities.

Defense:

  • Install Code (Pre-loaded keys): Burning unique keys into devices at the factory so joining the network doesn't require over-the-air transmission.
  • Disable Default Trust Center Keys: Disable industry-known default values to prevent direct exploitation.
  • Firmware Signature Verification: Ensuring devices only accept legitimate firmware signed by the manufacturer, blocking downgrade attacks.

Host Penetration and Lateral Movement

Container Escape and the 4C Security Model

Container Escape attack vectors:

VectorDescription
Privileged ContainerStarting a container with full host privileges (--privileged), allowing direct control over host hardware and system resources; boundary effectively non-existent
Kernel VulnerabilityContainers share the same OS Kernel as the host; kernel vulnerabilities allow programs inside the container to break isolation and gain host control
Mounting Host FilesystemMounting sensitive host directories or the Docker control interface (Docker Socket) into the container, providing an entry point for host administration
Dangerous System CapabilitiesRetaining unnecessary high-risk system capabilities (e.g., arbitrary disk mounting, modifying network settings), which attackers use to escape isolation

Kubernetes 4C Security Model (Outside-in):

LevelEnglishChineseSecurity Focus
1CloudCloudCloud account least privilege (IAM), network security group restrictions on exposure
2ClusterClusterRole-Based Access Control (RBAC), network policies restricting Pod communication, API Server mandatory authentication
3ContainerContainerRunning as non-root, mounting read-only root filesystems, removing unnecessary system capabilities, regular image vulnerability scanning
4CodeCodeSecure coding, dependency vulnerability scanning (SCA), not hardcoding secrets in images
  • Defense Principle: Containers should run with least privilege, as non-root users, with read-only root filesystems, and only necessary system capabilities.
  • Container isolation relies on two OS mechanisms: Namespaces (isolating process, network, and filesystem views) + cgroups (limiting CPU/memory usage).
  • Containers share "shared infrastructure" risks similar to multi-tenancy security; defense strategies are similar.

Process Injection and Process Hollowing

Both are techniques for executing malicious code within the memory space of a legitimate process, allowing attackers to bypass whitelist protections and masquerade as normal processes.

TechniquePrincipleCharacteristicsDetection Method
Process InjectionWriting malicious code (Shellcode or DLL) into the memory of a running legitimate process, executing it under the identity of that process.Executable segments that do not belong to the original program appear in the memory of a legitimate process (e.g., explorer.exe).EDR monitors for anomalous behavior where "one process performs cross-process writing to another and triggers execution."
Process HollowingCreating a suspended instance of a legitimate process, clearing its memory content, injecting malicious code, and then resuming execution.The process name appears normal, but the actual code in memory does not match the executable on disk.EDR compares the actual content loaded in memory with the original executable on disk for discrepancies.

These techniques are viable because Windows provides APIs for cross-process operations, originally intended for debuggers, monitoring tools, and anti-malware software. Attackers repurpose these mechanisms for malicious ends. Windows APIs are divided into two layers:

  • Win32 API: High-level interfaces documented by Microsoft, exported by kernel32.dll, user32.dll, etc., providing capabilities like cross-process memory writing and creating threads in other processes.
  • Native API / NTAPI: Lower-level interfaces exported by ntdll.dll that map directly to Windows kernel system calls (Syscalls). Win32 APIs are essentially wrappers around NTAPI. Most NTAPI are undocumented but still callable. Since some security tools place monitoring hooks at the Win32 layer, attackers sometimes switch to NTAPI to bypass this detection.

Process Injection Attack Flow:

The target is a running process (e.g., explorer.exe), with the goal of forcing it to execute the attacker's code unknowingly.

  1. Obtain access to the target process: Call OpenProcess with the target's PID to request a Handle from the OS. The Handle is the credential for all subsequent cross-process operations, signifying "the OS allows me to operate on this process." Sufficient privileges (usually Administrator) are required.
  2. Allocate space in the target process memory: Call VirtualAllocEx (Ex denotes cross-process capability) to allocate a blank region in the target's virtual address space, setting it to PAGE_EXECUTE_READWRITE (RWX) so it can be written to and executed.
  3. Write malicious code: Call WriteProcessMemory using the Handle from step 1 to write the malicious Shellcode directly into the memory address allocated in step 2. The code is now in the target's memory but not yet executing.
  4. Trigger execution: Call CreateRemoteThread (Win32) or the underlying NtCreateThreadEx (NTAPI) to create a new thread within the target process, with the start address pointing to the malicious code just written. The attack is complete.

Process Hollowing Attack Flow:

Unlike process injection, the attacker does not invade an already running process; instead, they start a legitimate process and swap its contents.

  1. Start a legitimate process and immediately suspend it: Call CreateProcess with the CREATE_SUSPENDED flag to start a system process like notepad.exe or svchost.exe. The process is created, but the main thread is immediately suspended before executing any of its own code. This step is perfectly legitimate and does not trigger alerts.
  2. Clear legitimate code (Hollowing): Call the NTAPI NtUnmapViewOfSection to unmap and clear the original executable code from the memory of the suspended process. The process shell (PID, Handle, name) remains, but the content is gone.
  3. Inject malicious code: Call VirtualAllocEx to reallocate RWX memory in the empty shell, then call WriteProcessMemory to write the malicious Payload.
  4. Tamper with the entry point: Call GetThreadContext to obtain the CPU register state of the suspended thread. At this point, the thread is stopped in the ntdll startup stub. The entry point address is stored as a parameter in the EAX (32-bit) or RCX (64-bit) register, rather than the instruction pointer EIP/RIP. The attacker changes the value of EAX/RCX to the address of the malicious code and calls SetThreadContext to write it back.
  5. Resume the process: Call ResumeThread (Win32) or NtResumeThread (NTAPI) to unsuspending the thread. Once the process starts, it executes the attacker's malicious code, yet Task Manager and most tools still display it as the legitimate notepad.exe.

Does Windows monitor these behaviors?

The Windows kernel itself does not block these API calls because they have legitimate uses, but there are several layers of restrictions:

  • Access privilege threshold: OpenProcess requires sufficient privileges. Protected processes marked as Protected Process Light (PPL) (e.g., lsass.exe, antivirus engine processes) cannot have a writable Handle obtained, even by an Administrator, effectively blocking the injection path.
  • Optional protection mechanisms: Since Windows 10, Arbitrary Code Guard (ACG) has been available. Once enabled for a process, it prohibits dynamic creation or modification of executable memory pages, directly blocking the VirtualAllocEx RWX allocation technique. However, ACG must be declared by the process itself and is not a system default.
  • Security tool monitoring: Windows Defender and third-party EDRs subscribe to kernel events via ETW (Event Tracing for Windows) to detect anomalous call sequences, such as "allocating RWX memory across processes followed immediately by a write and remote thread creation." While the kernel design permits these, they generate telemetry data for analysis, upon which security tool alert logic is built.

Common target processes: svchost.exe, explorer.exe, notepad.exe, and other system processes, as security tools typically do not deeply inspect these "trusted" processes.

HTTP Request Smuggling

When there is a discrepancy in how the front-end proxy server (e.g., CDN, load balancer) and the back-end server parse HTTP request boundaries, an attacker can "smuggle" hidden malicious requests within a single connection.

Why the discrepancy? HTTP has two ways to indicate request length, and the specification does not mandate priority when both are present:

  • Content-Length (CL): Declares the total length directly ("This package is 100 bytes total").
  • Transfer-Encoding: chunked (TE): Data is sent in chunks, each preceded by its length, ending with 0 ("Send in batches, stop when an empty batch is seen").

If the front-end and back-end trust different headers, they will cut the same request at different places. The "excess part" left in the back-end buffer is mistaken for the start of the next request.

CL.TE Attack Flow (Most common):

The attacker constructs a request containing both CL and TE, hiding malicious content after the TE termination marker:

http
POST / HTTP/1.1
Host: victim.com
Content-Length: 44          ← Front-end uses CL: 44 bytes body, forwards all to back-end
Transfer-Encoding: chunked  ← Back-end uses TE: Parses by chunk, stops at 0

# ── Back-end parsing range ─────────────────────────────────────────
0                           ← 0-length chunk, back-end considers request finished (TE termination)

# ── Residual buffer: Back-end stopped, content below attaches to next request ───────────
GET /admin HTTP/1.1         ← Smuggled content, pollutes next user request
Host: victim.com
# ── Front-end forwarding ends (44 bytes total) ──────────────────────────────
Diagram

Two-step Cookie Theft Mechanism:

Since the response is sent back to the victim rather than the attacker, the attacker needs to use an endpoint that stores data (e.g., comments, search history) as a relay:

Step 1: The attacker smuggles a POST with an unfinished body targeting a storage endpoint:

http
[Back-end buffer residual Attacker smuggled]
POST /post/comment HTTP/1.1
Host: victim.com
Content-Length: 999      ← Intentionally large, forcing back-end to wait for more input

csrf=xxx&comment=        ← Body intentionally truncated, waiting for victim's request to attach

Step 2: The next user's normal request attaches, and the back-end treats it as part of the POST body:

http
POST /post/comment HTTP/1.1
...

csrf=xxx&comment=GET /home HTTP/1.1  ← Start of user request treated as comment content
Host: victim.com
Cookie: session=abc123               ← Cookie stored along with comment

The back-end stores the entire segment as a comment. The attacker then sends a GET /post/X to view the comment and reads the user's Cookie. The victim's browser receives an unexpected comment submission response.

TE.CL Attack Structure (Front-end uses TE, back-end uses CL, roles reversed):

http
POST / HTTP/1.1
Host: victim.com
Transfer-Encoding: chunked  ← Front-end uses TE: Reads all chunks then forwards
Content-Length: 3           ← Back-end uses CL: Stops after reading 3 bytes of body

# ── Back-end parsing range (first 3 bytes of body) ──────────────────────────
1a                          ← chunk size header; back-end reads "1a\r" (3 bytes) and stops
# ── Residual buffer: Back-end stopped, content below attaches to next request ──────────
GET /admin HTTP/1.1         ← Smuggled content, pollutes next user request
Host: victim.com

# ── Front-end forwarding ends ─────────────────────────────────────────
0                           ← Front-end TE termination chunk (back-end already stopped, ignores this)

After the back-end reads the CL=3 content, the remainder of the chunk stays in the buffer. The pollution mechanism is the same as CL.TE, just with roles reversed.

TE.TE Attack Structure (Both use TE, but one does not understand the obfuscated version):

http
POST / HTTP/1.1
Host: victim.com
Transfer-Encoding: chunked   ← Standard TE header
Transfer-Encoding: xchunked  ← Obfuscated TE header (non-standard; one side identifies, other ignores)

# ── Side that identifies TE (parses by chunk) ────────────────────────
0                            ← Parses until here: 0-length chunk, request ends
# ── Side that cannot identify TE: Degrades to CL parsing ─────────────────────
# ── Residual buffer: Degraded side parses by CL, content below attaches to next request ────
GET /admin HTTP/1.1          ← Smuggled content, pollutes next request
Host: victim.com

One side fails to identify the obfuscated TE header and ignores it, effectively degrading to the CL.TE or TE.CL scenario, with the same subsequent pollution mechanism.

Attack VariantFront-end ParsingBack-end ParsingEffect
CL.TEContent-LengthTransfer-EncodingFront-end forwards complete request, back-end cuts off early, remainder pollutes next request
TE.CLTransfer-EncodingContent-LengthFront-end cuts off early, back-end reads excess content per total length, remainder pollutes next request
TE.TETE (parses obfuscated)TE (ignores obfuscated)Attacker writes slightly malformed TE header, causing one side to fail identification and switch parsing methods

Attack Impact:

  • Hijacking other users' requests (stealing Cookies, Session Tokens).
  • Bypassing front-end security controls (e.g., WAF, access control).
  • Executing arbitrary requests on the back-end.

Defense

The root cause is the HTTP/1.1 parsing discrepancy between the front-end proxy → back-end, which must be configured at the proxy layer. RFC 7230 mandates that TE takes precedence over CL when both are present; strict adherence by both ends eliminates the discrepancy.

LayerDefault StatusRisk
Browser → Front-end ProxyMostly HTTP/2 under HTTPS, Binary Frame mechanism, no CL/TE discrepancyNone
Front-end Proxy → Back-endNginx / HAProxy default to HTTP/1.1 for back-endAttack point
Back-end ApplicationASP.NET Core (Kestrel) follows RFC 7230, TE takes precedence over CLSecure itself, but cannot block requests already smuggled by proxy

Nginx (1.13.0+ has patched TE parsing logic, additional settings can be added)

Reject ambiguous requests and return 400:

nginx
# http {} block
map "$http_content_length:$http_transfer_encoding" $smuggling_risk {
    # Nginx concatenates the values of CL and TE from incoming headers with a colon :
    # If both have values, it matches "~.+:.+" (regex: at least one character on both sides), assigning 1 (high risk).
    "~.+:.+" 1;
    default   0;
}

# server {} block
if ($smuggling_risk) {
    return 400 "Bad Request: Multiple Length Indicators";
}

Upgrade to HTTP/2 upstream (fundamental solution, requires back-end support; Kestrel supports it by default):

nginx
proxy_http_version 2.0;

Proxy layer normalization (remove TE, back-end only sees CL):

nginx
proxy_set_header Transfer-Encoding "";

HAProxy (1.9+ has strict header parsing enabled by default, ACL can be added to force rejection of ambiguous requests):

haproxy
# frontend or listen block
http-request deny if { req.hdr_cnt(content-length) gt 0 } { req.hdr_cnt(transfer-encoding) gt 0 }

ASP.NET Core (Kestrel)

Kestrel already complies with RFC 7230; no extra configuration is needed. To leave warning logs at the Middleware layer for defense-in-depth:

csharp
app.Use(async (context, next) => {
    var headers = context.Request.Headers;
    if (headers.ContainsKey("Content-Length") && headers.ContainsKey("Transfer-Encoding")) {
        context.Response.StatusCode = 400;
        await context.Response.WriteAsync("Bad Request: Invalid Header Combination");
        return;
    }
    await next();
});

DNS Tunneling

Utilizes the DNS protocol (which usually allows UDP Port 53 traffic through firewalls) as a covert data transmission channel, encoding non-DNS data within DNS queries and responses.

AspectDescription
PrincipleAttackers set up their own DNS server. The victim host encodes stolen data into subdomains (e.g., dGVzdA.attacker.com) and sends it via DNS queries; the attacker's DNS server decodes it to retrieve the data.
UsageC2 communication (Command & Control), data exfiltration, bypassing Captive Portals (e.g., authentication walls in airports/cafes).
Detection IndicatorsAbnormally long subdomains, high-frequency DNS queries, abnormal TXT/NULL record query ratios, sudden spikes in queries for a single domain.
Common Toolsiodine, dnscat2, dns2tcp
DefenseDeep Packet Inspection (DPI) of DNS traffic, restricting internal DNS to forward only to trusted recursive resolvers, monitoring for abnormal DNS query lengths and frequencies.

Cross-Platform Attack Differences (Windows vs Linux)

Privilege Escalation

AspectWindowsLinux
Common TechniquesToken Manipulation (impersonating high-privilege users), UAC Bypass, Unquoted Service Paths (paths with spaces but no quotes, allowing malicious executables to be inserted), DLL HijackingSUID/SGID special execution permission abuse, sudo misconfiguration (allowing unauthorized commands), kernel exploit, Cron job misconfiguration, writable PATH directories
Key DifferencesWindows manages privileges via Tokens and Access Control Lists (ACLs); attackers often gain SYSTEM control by simulating high-privilege tokens.Linux manages privileges via User IDs (UID) and Group IDs (GID); programs with special execution bits (SUID) are the most common targets for escalation.
Detection FocusMonitor anomalous use of high-risk system privileges (e.g., debugging, impersonation).Regularly scan for anomalous files with SUID/SGID special permissions.

Persistence

AspectWindowsLinux
Common TechniquesRegistry Run keys (auto-execution on boot), Scheduled Tasks, Startup Folder, WMI event subscription, Service creationcrontab scheduling, Shell initialization scripts (.bashrc / .profile), systemd services, SSH authorized key injection
Key DifferencesThe Registry is a Windows-unique persistence vector, highly varied and stealthy.Linux persistence often relies on Shell initialization scripts or scheduling tools.
Detection FocusMonitor changes to startup-related Registry keys and Scheduled Task modifications.Monitor crontab changes, new systemd service files, and SSH authorized key modifications.

Lateral Movement

AspectWindowsLinux
Common TechniquesPsExec (remote command execution), WMI (Windows Management Instrumentation), RDP (Remote Desktop), WinRM (Windows Remote Management), DCOM (Distributed Component Object Model)SSH, Ansible / Salt configuration management tools, stolen SSH private keys, NFS network shares
Key DifferencesWindows domain environments have built-in remote management tools; attackers leverage existing infrastructure without bringing external tools.Lateral movement in Linux environments primarily relies on SSH; obtaining a private key allows spreading across multiple hosts.
Detection FocusMonitor anomalous connections for file sharing (SMB) and Remote Procedure Calls (RPC).Monitor anomalous SSH login sources and changes to SSH authorized key files.
Linux Privilege Escalation Detection Commands
bash
# Find all SUID files (potentially exploitable to execute as root)
find / -perm -4000 -type f 2>/dev/null

# Find all SGID files
find / -perm -2000 -type f 2>/dev/null

# Find both SUID and SGID
find / -perm /6000 -type f 2>/dev/null

# Check sudo configuration (which commands can run as root without password)
sudo -l

# Find writable cron directories and scripts
find /etc/cron* -writable -type f 2>/dev/null
ls -la /etc/cron.d/ /var/spool/cron/

# Find world-writable directories (potentially exploitable for PATH Hijacking)
find / -writable -type d 2>/dev/null | grep -v proc

# Check if /etc/passwd is writable (rare but fatal)
ls -la /etc/passwd /etc/shadow
  • SUID file lists can be cross-referenced with GTFOBins to confirm exploitable escalation paths.
  • Windows equivalent tool: LOLBAS (Living Off The Land Binaries and Scripts).

Credential Theft and Lateral Movement Techniques

Pass-the-Hash (PtH)

The Windows NTLM authentication protocol uses a Challenge-Response mechanism; the server only needs to verify the MD4 hash of the password, not the plaintext password itself. Once an attacker obtains the hash, they can impersonate a legitimate user to log into other hosts without cracking the original password.

NTLM Background

The default authentication protocol before Windows 2000, later replaced by Kerberos, but retained as a fallback for workgroup environments, local account authentication, and scenarios where Kerberos is unavailable.

  • Prerequisite: Obtain NTLM hashes from the local password database (SAM, Security Account Manager) or memory.
  • Impact: Obtaining a Domain Admin hash allows lateral movement across the entire Windows domain.
  • Defense: Disable NTLM authentication (use Kerberos), enable Credential Guard (protects hashes in memory from being read), limit the login scope of privileged accounts.

Pass-the-Ticket (PtT)

Kerberos authentication uses Tickets instead of passwords. Attackers steal tickets and inject them into their own connections to access resources as the ticket holder, without needing the password or hash.

  • Difference from PtH: PtH uses NTLM hashes; PtT uses Kerberos tickets. PtH is ineffective once Kerberos is enabled, leading attackers to use PtT.
  • Golden Ticket: Kerberos has a special account (krbtgt) responsible for issuing all tickets. Obtaining its password hash allows forging arbitrary user TGTs (Ticket-Granting Tickets), effectively acting as a master key for the entire domain.
  • Silver Ticket: Forges access tickets for a single service only. The scope is more limited than a Golden Ticket, but it is harder to detect because it does not require requests to the Kerberos server.
  • Defense: Periodically reset the krbtgt account password (must be reset twice to fully invalidate), monitor for tickets with abnormally long expiration times, deploy Privileged Access Management (PAM).

krbtgt Account and the Two-Reset Requirement

krbtgt is a built-in AD domain service account. The KDC uses its password hash to encrypt and sign all TGTs, making it the most sensitive secret in the domain. For compatibility, AD retains both the "current password" and the "previous password" for krbtgt, accepting both during ticket verification. Resetting once leaves the stolen old password as the "previous password," keeping forged Golden Tickets valid. After the second reset, the old password is completely wiped from AD, and Golden Tickets finally expire. A waiting period (roughly equal to the default TGT expiration of 10 hours) between resets is required to let existing legitimate tickets expire naturally, preventing service disruption.

Kerberoasting

Kerberos allows any logged-in domain user to request a service ticket from the Key Distribution Center (KDC), which is encrypted with the service account's password hash. Attackers request the ticket and take it offline for brute-force cracking to recover the service account's plaintext password.

  • Why it works: Service accounts (e.g., database service accounts) often have long-lived, weak passwords; any authenticated domain user can request a service ticket (SPN, Service Principal Name) without special privileges.
  • Attack Steps: Enumerate accounts with SPNs → Request service tickets → Offline brute-force.
  • Defense: Use 25+ character random passwords for service accounts; use gMSA (Group Managed Service Account, where Active Directory automatically manages password rotation); monitor for anomalous spikes in service ticket requests.

DCSync

Attackers leverage the Active Directory directory replication protocol (MS-DRSR, Directory Replication Service Remote Protocol) to impersonate a Domain Controller (DC) and request account password hashes from other DCs, without needing to log into a DC or execute any code on it.

  • Prerequisite: The attacker account must have "Replicating Directory Changes" (DS-Replication-Get-Changes-All) permissions, usually requiring a Domain Admin or an account explicitly granted this permission.
  • Typical Usage: Steal the krbtgt account hash to create Golden Tickets, or batch-extract password hashes for the entire domain.
  • Why it's hard to detect: Network traffic is indistinguishable from normal DC replication; no malicious tools are carried, making it a form of Living off the Land.
  • Tool: Mimikatz lsadump::dcsync /domain:corp.local /user:krbtgt.
  • Defense: Monitor replication requests originating from non-DC machines (Windows Event ID 4662); strictly limit who is granted "DS-Replication-Get-Changes-All"; deploy Privileged Access Management (PAM).

Living off the Land

Attackers do not carry their own tools but instead use legitimate tools already present on the target system to execute malicious operations. Because these tools are digitally signed and built-in, they do not trigger traditional antivirus alerts.

PlatformTermCommonly Abused ToolsMalicious Usage Examples
WindowsLOLBinscertutil.exe, mshta.exe, regsvr32.exe, rundll32.exe, powershell.exeUse certutil to download malicious files, use mshta to execute scripts (these are built-in, AV won't block)
LinuxGTFOBinscurl, wget, python, perl, find, vimUse find's SUID to escalate privileges and execute shell, use curl to download and execute malicious scripts
  • Why it's hard to detect: These tools are legitimate (administrators use them too); context (who, when, from where, with what parameters) is required to determine if the usage is malicious.
  • Relation to Fileless Malware: Living off the Land is the primary means of fileless attacks, where malicious code exists only in memory and is never written to disk, making it even harder for traditional AV to detect.
  • Defense: Application Whitelisting (AppLocker / WDAC), PowerShell Constrained Language Mode, Script Block Logging, EDR behavior detection.
  • Reference: LOLBAS Project (Windows), GTFOBins (Linux).

Detection Indicators and Emerging Threats

Indicators of Compromise (IOC) and Indicators of Attack (IOA)

Comparison AspectIOC (Indicator of Compromise)IOA (Indicator of Attack)
NatureForensic evidence left after an attack has occurredBehavioral patterns during an ongoing attack
TimingPost-facto (Reactive)Real-time (Proactive)
Typical ExamplesMalicious file Hash, C2 IP/Domain, malicious Registry Key, anomalous file pathsProcess injection behavior, anomalous PowerShell call patterns, account logging into multiple hosts in a short time
ToolsThreat Intelligence Platform (TIP), SIEM matching rules, YARA rulesEDR / XDR behavior analysis, UEBA (User and Entity Behavior Analytics)
LimitationsAttackers can easily change Hashes/IPs (low-cost avoidance)Requires mature detection capabilities and baseline establishment
  • IOCs have a short lifecycle (they become useless once the attacker changes tools), but are low-cost to establish.
  • IOAs focus on "behavior" rather than "characteristics." Even if the attacker changes tools, the behavioral pattern remains similar, making detection more durable.
  • In practice, they are complementary: IOCs are for quickly matching known threats, while IOAs are for detecting unknown or novel attacks.
  • IOCs are like "fingerprints at a crime scene," while IOAs are like "suspicious behavior on surveillance cameras."
  • The tactics and techniques described in the MITRE ATT&CK framework are essentially IOAs and can serve as sources for Threat Hunting hypotheses.

Threat Intelligence and Security Assessment

Threat Hunting

Threat Hunting is a proactive, hypothesis-driven search method where security personnel actively look for potential threats in the environment that have not yet triggered alerts, complementing the reactive incident response to SIEM alerts.

AspectThreat HuntingIncident Response
TriggerProactive (hypothesis-driven, no alert needed)Reactive (triggered by SIEM / IDS alerts)
GoalFind potential attackers or IOCs not yet detectedRespond to known, confirmed incidents
ScenariosAPT lurking, novel attack techniques, detection tool blind spotsContainment, eradication, and recovery after a security incident

Threat Hunting Process:

  1. Formulate Hypothesis: Based on threat intelligence (CTI), MITRE ATT&CK tactics, or past incidents, propose a hypothesis like "attackers might be using X technique."
  2. Collect and Search Data: Search for IOCs or IOAs related to the hypothesis in EDR, SIEM, and logging systems.
  3. Analyze and Identify: Distinguish malicious behavior from normal noise to confirm if a real threat exists.
  4. Respond and Improve: If a threat is found, transition to Incident Response; if not, convert the search logic into automated detection rules to continuously strengthen detection capabilities.

Diamond Model

The Diamond Model is a foundational framework for threat intelligence analysis. Every intrusion event can be described by four core dimensions, forming a diamond.

DimensionDescriptionExample
AdversaryThe actor launching the attackNation-state APT groups, cybercrime syndicates
CapabilityTools, malware, and exploit techniques usedCobalt Strike, Log4Shell exploit
InfrastructurePhysical resources controlled or used by the attackerC2 servers, compromised relay machines, malicious domains
VictimThe target of the attackSpecific enterprises, critical infrastructure, specific individuals
Diagram
  • Core assumption: Attackers need Capability and Infrastructure to affect a Victim; cutting any link disrupts the attack.
  • Complementary to MITRE ATT&CK: The Diamond Model describes "who, what, where, and whom" (overall relationships), while ATT&CK describes "how" (technical details).
  • Community extension: Meta-diamond links multiple related events to attribute them to the same APT group.

Threat Actor Classification Table

Actor TypeMotivationSkill LevelResource ScaleTypical Targets
Script KiddieBragging, curiosityLow (uses off-the-shelf tools)IndividualRandom targets, website defacement
CybercriminalMoneyMedium to HighCriminal syndicatesFinancial institutions, personal data
HacktivistIdeology, social justiceMediumOrganization/CollectiveGovernment agencies, corporate websites
Insider ThreatRevenge, money, coercionHigh (has internal access)IndividualEmployer systems and data
Nation-StateNational interest, espionageExtremely HighNational resourcesCritical infrastructure, government, military-industrial
APTLong-term lurking, intelligenceExtremely HighNation or large orgHigh-value targets, supply chains

Threat Intelligence Source Classification

TypeDescriptionRepresentative Orgs/Resources
CommercialPaid threat intelligence services and OSINT toolsSecurity vendors, CVE, MITRE ATT&CK, VirusTotal
GovernmentThreat bulletins from national CERTs and law enforcementTWCERT/CC, US-CERT, NCSC
CommunityIndustry ISACs and open-source sharing platformsFinancial FS-ISAC, Energy E-ISAC, MISP

Threat Intelligence Sharing: TLP 2.0

CISA (Cybersecurity and Infrastructure Security Agency) adopts TLP (Traffic Light Protocol) 2.0 as the standard for threat intelligence sharing, using colors to indicate the dissemination scope. TLP applies regardless of the medium (email, reports, presentations).

LabelDissemination ScopeDescription
TLP:REDOriginal recipients onlyDo not forward; restricted to the original sharing context (e.g., meeting attendees).
TLP:AMBER+STRICTWithin the recipient's organizationRestricted to a "need-to-know" basis within the organization; no cross-organization sharing.
TLP:AMBERRecipient's org and direct clientsCan be shared on a need-to-know basis within the org and with direct business clients.
TLP:GREENWithin the security communityCan be shared widely within the security community (e.g., ISACs, forums); no public internet publishing.
TLP:CLEARUnlimitedNo dissemination restrictions; can be shared publicly on the internet.

TLP 2.0 Key Points

  • Restrictions from loose to strict: CLEAR → GREEN → AMBER → AMBER+STRICT → RED.
  • TLP:AMBER vs TLP:AMBER+STRICT: AMBER allows sharing with direct clients; AMBER+STRICT is internal-only.
  • 2.0 vs 1.0 main differences: 2.0 renames "WHITE" to "CLEAR," adds "AMBER+STRICT," and clearly defines the boundaries of the "Community."

Threat Intelligence Standards (STIX / TAXII / CVE / CVSS)

Four Categories of Threat Intelligence (by User Level)

The four levels are arranged by abstraction, corresponding to decision-making needs from high to low: "Trend Judgment → Attack Warning → Technique Analysis → Indicator Blocking."

TypeEnglishTarget UserTypical Example
Strategic IntelligenceStrategic IntelligenceExecutives, CISO, Board of DirectorsThreat trends, attacker motivations, geopolitical risks
Operational IntelligenceOperational IntelligenceSOC Analysts, CSIRTDetails and targets of specific ongoing or imminent attack campaigns
Tactical IntelligenceTactical IntelligenceSecurity Architects, Red TeamsAttacker TTPs, MITRE ATT&CK mapping
Technical IntelligenceTechnical IntelligenceFirewall/SIEM AdministratorsSpecific IOCs (IP addresses, malicious hashes, malicious domains)

💡 Glossary Quick Reference

  • CISO: Chief Information Security Officer
  • SOC: Security Operations Center
  • CSIRT: Computer Security Incident Response Team
  • TTPs: Tactics, Techniques, Procedures
  • SIEM: Security Information and Event Management
  • IOC: Indicator of Compromise

STIX / TAXII:

STIX defines the structured format for threat intelligence, while TAXII handles the transport. They are typically used together to form the foundation for automated threat intelligence exchange.

ItemEnglishDescription
STIX 2.1Structured Threat Information eXpressionExpresses threat intelligence in a structured JSON format, covering object types such as attack patterns, malicious indicators IOCs, and threat actor organizations
TAXIITrusted Automated eXchange of Indicator InformationThe transport protocol for STIX data, defining two exchange modes: Collection (pull) and Channel (push)

CVE / CWE / CVSS:

CVE records specific vulnerability events, CWE describes the weakness types behind vulnerabilities, and CVSS measures their severity. Together, they form the foundational vocabulary for vulnerability management.

ItemEnglishDescription
CVECommon Vulnerabilities and ExposuresA unique vulnerability numbering system with the format CVE-Year-SequenceNumber (e.g., CVE-2024-12345). Maintained by MITRE; NVD (maintained by NIST) provides search and detailed analysis
CWECommon Weakness EnumerationA software weakness classification system maintained by MITRE, describing weakness types (e.g., SQL Injection, Buffer Overflow) rather than specific vulnerability events
CVSSCommon Vulnerability Scoring SystemVulnerability severity scoring (0.0–10.0), maintained by FIRST

CVSS v4.0 (released by FIRST in November 2023) is the current version. The Base Score consists of 11 metrics grouped into three sets:

Exploitability Metrics

MetricAbbreviationOptions (High to Low)Description
Attack VectorAVNetwork > Adjacent > Local > PhysicalSame as v3.x
Attack ComplexityACLow > HighDifficulty for an attacker to actively circumvent existing defenses
Attack RequirementsATNone > PresentNew in v4.0: Preconditions required for a successful attack (e.g., specific race conditions, configuration states), separated from AC
Privileges RequiredPRNone > Low > HighSame as v3.x
User InteractionUINone > Passive > Activev3.x only had None / Required; v4.0 adds Passive (user triggered passively)

Vulnerable System Impact

MetricAbbreviationOptions
Confidentiality ImpactVCHigh / Low / None
Integrity ImpactVIHigh / Low / None
Availability ImpactVAHigh / Low / None

Subsequent System Impact

MetricAbbreviationOptions
Confidentiality ImpactSCHigh / Low / Negligible
Integrity ImpactSISafety / High / Low / Negligible
Availability ImpactSASafety / High / Low / Negligible

CVSS Severity Ratings:

RatingScore Range
None0.0
Low0.1–3.9
Medium4.0–6.9
High7.0–8.9
Critical9.0–10.0

Key Differences: CVSS v3.x vs v4.0

Aspectv3.xv4.0
Impact Scope RepresentationSingle Scope metric (Changed / Unchanged)Split into Vulnerable System (VC/VI/VA) and Subsequent System (SC/SI/SA) sets, scored individually
Attack ComplexityAC covers both technical difficulty and preconditionsAC (difficulty to circumvent defenses) and AT (preconditions for success) are split into two independent metrics
User InteractionNone / RequiredNone / Passive / Active (distinguishes between passive triggering and active operation)

CVE vs CWE vs CVSS

ItemPositioningAnalogy
CVEUnique ID for a specific vulnerability"A window in a specific building is broken" (Specific event)
CWEClassification catalog of weaknesses"Poor window lock design" (Weakness type)
CVSSSeverity score of a vulnerability"How high is the risk of this broken window" (Severity level)
  • A CVE usually maps to one or more CWE categories (e.g., CVE-2021-44228 maps to CWE-502).
  • CWE Top 25 and OWASP Top 10 (comparison table in document) are complementary; the former focuses on code-level weakness classification, while the latter focuses on Web application risks.

Penetration Testing Types and Scope

TypeEnglishInformation Disclosure LevelTesting MethodSimulated Scenario
Black BoxBlack BoxNo internal informationExternal attacker perspective, only knows target organization nameExternal hacker attack
Grey BoxGrey BoxPartial internal informationProvided with basic network architecture or employee listDisgruntled employee or partner attack
White BoxWhite BoxFull internal informationProvided with system documentation, source code, network diagramsInsider threat or comprehensive security assessment

Applicability of White/Grey/Black Box

Black/Grey/White box are universal testing methodology dimensions that describe "how much information the tester has about the target," not exclusive to penetration testing:

DomainApplication Method
Penetration TestingBlack Box = External attacker perspective; White Box = Insider/full documentation perspective
Software Testing/QAWhite Box = Unit testing with source code; Black Box = Testing interface behavior only (functional testing)
Secure Code ReviewWhite Box = Source code available for review; Black Box = Only executable available for analysis (reverse engineering)

Penetration Testing Phases:

PhaseEnglishActivityTool ExampleOutput
ReconnaissanceReconnaissanceOSINT, DNS queries, port scanningNmapTarget asset list
ScanningScanningVulnerability scanning, service fingerprintingNessus, NiktoVulnerability list
Gaining AccessGaining AccessVulnerability exploitation, password attacksMetasploitInitial foothold
Maintaining AccessMaintaining AccessBackdoor implantation, privilege escalationCobalt StrikePersistent access
Covering TracksCovering TracksLog cleaning, trace removalManual or scriptsConceal attack evidence
Common Nmap Scanning Commands

Nmap (Network Mapper) is an open-source network exploration and security auditing tool, widely used in the reconnaissance phase of penetration testing. Core functions include host discovery, open port scanning, service version identification, and OS fingerprinting. It supports various scanning techniques such as TCP SYN (half-open), UDP, and XMAS, and includes the NSE (Nmap Scripting Engine) for advanced tasks like vulnerability detection and brute-forcing.

bash
# TCP SYN scan (half-open, requires root)
sudo nmap -sS -p 1-1024 192.168.1.0/24

# Full scan: SYN + version detection + OS detection + default scripts
sudo nmap -sS -sV -O -sC target.example.com

# UDP scan (slower, commonly used for DNS/SNMP)
sudo nmap -sU -p 53,161 target.example.com

Defense Techniques

Common Security Defense Techniques Table

The following are general defense techniques across various attack methods. For the principles and specific defenses of each attack method, refer to the Common Software Vulnerability Exploitation Table.

Defense TechniqueFull NameDefense PrincipleApplicable Attack Methods
ASLRAddress Space Layout RandomizationRandomizes memory addresses of Stack, Heap, and shared libraries at each execution, preventing attackers from predicting target addresses.Buffer Overflow, Heap Spray, ROP
DEP / NXData Execution Prevention / No-ExecuteMarks memory segments as "non-executable," preventing direct execution even if an attacker injects Shellcode.Buffer Overflow, Heap Spray
Stack CanaryStack CanaryInserts a random value between the buffer and the return address, verifying it before function return. If overwritten → terminates the process immediately.Buffer Overflow
CFIControl Flow IntegrityRestricts indirect jumps (call, ret) to pre-approved legal targets, preventing attackers from hijacking control flow.ROP
Shadow StackShadow Stack (Intel CET)Hardware-level maintenance of a backup of return addresses (Shadow Stack); compares addresses on ret, terminating if they mismatch.ROP
Constant-time ImplementationConstant-time AlgorithmEnsures all execution paths take the same time, eliminating timing differences. .NET provides CryptographicOperations.FixedTimeEquals().Timing Side-channel attacks
KPTIKernel Page-Table IsolationUses different page tables for user mode and kernel mode, preventing user mode from inferring kernel memory content via cache timing.Meltdown
Retpoline / IBRSReturn Trampoline / Indirect Branch Restricted SpeculationPrevents branch prediction attacks during CPU speculative execution. Retpoline is software-level; IBRS is a hardware microcode update.Spectre
SandboxSandboxRestricts programs to an isolated environment, preventing impact on the main system or access to other resources even if compromised.Zero-day, Fileless Malware, RCE

Firewall Type Comparison Table

TypeOSI LayerCore MechanismProsCons
Packet FilterL3–L4Filters packet-by-packet based on static rules (IP, Port, Protocol)Fast, low resource consumptionStateless, cannot identify connection context; cannot inspect Payload.
Stateful InspectionL3–L4Tracks TCP/UDP connection state, verifies packets belong to established connectionsMore secure than packet filtering, prevents spoofed packetsStill cannot inspect application-layer content.
Application ProxyL7Terminates and reconstructs connections, deeply parses application protocolsCan detect and block application-layer attacks (e.g., XSS, SQLi)High latency, requires specific proxy deployment for each protocol.
NGFW (Next Generation Firewall)L3–L7Integrates Stateful + DPI (Deep Packet Inspection) + IPS + Application IdentificationSingle device covers multi-layer protectionHigh cost, complex configuration.
WAF (Web Application Firewall)L7Deeply parses HTTP/HTTPS traffic, identifies/blocks Web attacks (XSS, SQLi, CSRF, etc.) based on signatures or behavioral rulesDirectly maps to OWASP Top 10; supports Virtual Patching to block vulnerabilities before code fixesProtects Web traffic only; rules require continuous maintenance, false positives may affect normal requests.

Core Differences Between Firewalls

  • Packet Filter = Only checks "address" and "door number" (IP + Port).
  • Stateful Inspection = Remembers "whether you knocked first" (connection state).
  • Application Proxy = Reads "letter content" before deciding whether to pass.
  • NGFW = All of the above, plus application identification (e.g., distinguishing BitTorrent vs HTTP/443).
  • WAF = Only reads "HTTP letters," specializes in Web attacks; NGFW is a generalist, WAF is a specialist.
  • Windows Defender Firewall = Stateful Inspection + Application-aware filtering. Implemented via WFP (Windows Filtering Platform) at the bottom layer, it is a second-generation (stateful) firewall with added application-level rule capabilities. Not an NGFW: Lacks DPI, IPS engines, and application-layer intelligent identification.
    • Inbound Rules: Controls traffic initiated externally entering the machine. Blocks all non-whitelisted inbound connections by default. Use case: Machine acts as a server accepting external connections (e.g., RDP, Web Server).
    • Outbound Rules: Controls traffic initiated by the machine. Allows all outbound connections by default. Use case: Actively blocking specific programs or ports from accessing the internet.
    • Example: Application server connecting to SQL Server: SQL Server needs an Inbound Rule for Port 1433 to allow external connections; the application server needs an Outbound Rule to allow connection to Port 1433. The application server does not need an inbound rule for query results; Stateful Inspection already recorded the connection, so SQL Server's response is treated as part of an established connection.
    • Application Rules: Rules match the full executable path (e.g., C:\Program Files\Google\Chrome\Application\chrome.exe), not just the filename. WFP obtains the process path in the kernel network stack, deciding to allow or block regardless of the port used. This is OS-level process matching, different from NGFW application identification (which parses packet payloads).
    • Bypass: Renaming a malicious program to chrome.exe is ineffective because the full path won't match. A viable bypass is process injection, injecting malicious code into a legitimate chrome.exe. Traffic originates from a legitimate process, WFP sees the correct path, and the rule allows it.
    • Profile: Rules can be applied based on connection context (Domain, Private, Public), e.g., allowing a program on home networks but blocking it on public Wi-Fi.

Firewall Evolution

GenerationTechnologyOSI LayerKey Milestone
1st GenPacket FilterL3–L4Proposed by DEC in 1988, checks packet headers only.
2nd GenStateful InspectionL3–L4Commercialized by Check Point in 1994, tracks connection state.
3rd GenApplication Gateway / ProxyL7Full application-layer protocol parsing, intercepts application-layer attacks.
NGFWDPI + IPS + App ID + StatefulL3–L7Defined by Gartner in 2009, integrates multiple technologies into one device.
  • WAF is not part of the firewall evolution, but an L7 protection device designed for Web traffic, complementary to NGFW.
  • Firewalls capable of identifying application-layer (L7) protocols started with the 3rd generation (Application Proxy); NGFW integrates DPI, IPS, and App ID into a single device for better L7 visibility.

DMZ and Micro-segmentation

DMZ (Demilitarized Zone) Architecture:

Diagram
  • DMZ hosts servers that provide external services but should not directly access the internal network.
  • Two-firewall DMZ architecture is more secure than a three-legged DMZ architecture.

Micro-segmentation:

  • Establishes fine-grained security segments within a data center using software-defined methods, where each workload (VM / Container / Application) has independent security policies.
  • Difference from traditional VLAN segmentation: VLANs are network-segment based; micro-segmentation can be as granular as a single host or workload.
  • Micro-segmentation is the implementation of Zero Trust Architecture at the network layer, limiting an attacker's lateral movement.

IDS vs IPS Comparison Table

AspectIDS (Intrusion Detection System)IPS (Intrusion Prevention System)IDPS (Intrusion Detection and Prevention System)
Full NameIntrusion Detection SystemIntrusion Prevention SystemIntrusion Detection and Prevention System
DeploymentOut-of-band: Copies traffic for analysis, not in the main path, does not affect packet deliveryInline: All traffic must pass through it, allows real-time interceptionInline, same as IPS
ReactionDetects and alerts only, no interceptionBlocks or drops malicious packets immediately upon detectionCan choose "Alert only" or "Block" based on rules; supports both modes
Traffic ImpactNone (does not interfere)Latency risk (requires real-time analysis of every packet)Latency risk (inline deployment)
False Positive CostLow (at most one extra alert)High (may block legitimate traffic, affecting services)Depends on mode; blocking mode same as IPS, detection mode same as IDS
DetectionSignature-based / Anomaly-basedSame as IDS, but with real-time blockingSame as IDS / IPS

Differences Between IDS, IPS, and IDPS

  • IDS = Alarm, out-of-band, notifies only, low false positive cost.
  • IPS = Security guard, inline, blocks directly, false positives may block legitimate traffic.
  • IDPS = Integrates both, can switch between "Detection mode" and "Blocking mode" based on rules; modern enterprises almost exclusively deploy IDPS (e.g., Snort, Suricata).

Detection Method Classification

Detection MethodPrincipleProsCons
Signature-basedMatches against a database of known attack signaturesPrecise, low false positive rateCannot detect unknown attacks (Zero-day).
Anomaly-basedEstablishes a baseline of normal behavior, alerts on deviationCan detect unknown attacksRequires tuning period, higher false positive rate.
Behavior-basedAnalyzes behavioral patterns and attack chains (e.g., continuous probing → escalation → lateral movement)Can detect complex APT attacksHigh computational overhead, complex rule maintenance.
  • The fundamental reason Signature-based cannot detect Zero-days: The signature database only contains "known attacks"; never-before-seen techniques trigger no rules.
  • The fundamental reason Anomaly-based has high false positives: "Normal behavior baseline" is difficult to define precisely; legitimate abnormal operations (e.g., batch backups, large queries) are easily misidentified as attacks.

Detection Rule Languages: Snort / YARA / Sigma

IDS/IPS and SIEM each have their own rule languages, targeting different layers:

ToolDetection TargetTypical Scenario
SnortNetwork PacketsIDS/IPS deployed near firewalls, real-time packet signature matching
YARAFile / Memory ContentMalware analysis, endpoint scanning, Threat Hunting
SigmaSIEM Log EventsWrites detection logic in platform-agnostic YAML, then converts to specific SIEM query syntax

Snort: A packet signature rule language, also the mainstream format for open-source IDPS like Suricata. Rules describe source IP/Port, destination, and Payload keywords, triggering alerts or blocks.

YARA: Describes malware "fingerprints" using strings, regex, and condition combinations. Targets static files or memory snapshots, not network traffic. One YARA rule can identify an entire malware family, even if samples are renamed or lightly obfuscated.

Three Blocks of a YARA Rule:

BlockPurposeDescription
metaMetadata (non-functional)Records author, description, date, CVE references, etc. Does not affect logic, for human reading only.
stringsFeature DefinitionDeclares string features to match, can be text ("text"), hex byte sequences ({ 6A 40 }), or regex (/regex/); supports modifiers like nocase and wide (UTF-16).
conditionScanning Logic (Heart of the rule)Uses Boolean logic (and, or, not) combined with strings variables and other attributes (e.g., filesize) to determine a match. Example: any of ($s*) matches any string; 2 of them matches at least two; $s1 and filesize < 500KB combines conditions.

Sigma: Solves the problem of incompatible SIEM query syntaxes. Security researchers write detection logic in Sigma, then use tools (like sigma-cli) to convert it into Splunk SPL, Elastic KQL, Microsoft Sentinel KQL, etc., achieving "write once, deploy on multiple platforms."

Common Rule Examples

Snort — Detecting SQL Injection in HTTP Traffic

snort
alert tcp any any -> $HOME_NET 80 (
  msg:"SQL Injection Attempt";
  flow:to_server,established;
  content:"' OR '1'='1"; nocase;
  sid:1001; rev:1;
)
  • alert: Triggers an alert on match (change to drop to block).
  • flow:to_server,established: Only monitors established connections from client to server, reducing false positives.
  • content: Matches specific strings in the Payload; nocase ignores case.
  • sid: Unique rule ID; rev: Version number.

YARA — Identifying Files with Mimikatz Strings

yara
rule Mimikatz_Strings {
  meta:
    description = "Detects Mimikatz credential dumping tool"
    author      = "example"
  strings:
    $s1 = "mimikatz" nocase
    $s2 = "sekurlsa::logonpasswords" nocase
    $s3 = "lsadump::sam" nocase
  condition:
    any of ($s*)
}
  • strings: Defines string features to match, supports nocase, wide (UTF-16).
  • condition: any of ($s*) means trigger if any string starting with $s is matched.
  • Can scan disk files or memory snapshots without knowing the exact filename or hash.

Sigma — Detecting PowerShell Encoded Command Execution (Common Obfuscation)

yaml
title: PowerShell Encoded Command Execution
status: stable
description: Detects PowerShell execution with -EncodedCommand flag, commonly used to obfuscate malicious scripts
logsource:
  category: process_creation
  product: windows
detection:
  selection:
    Image|endswith: '\powershell.exe'
    CommandLine|contains:
      - ' -EncodedCommand '
      - ' -enc '
  condition: selection
falsepositives:
  - Legitimate administrative scripts
level: medium
  • logsource: Specifies log source type (Windows process creation event).
  • detection.selection: Matches field values; CommandLine|contains supports multiple keywords (OR logic).
  • condition: selection means all conditions must be met (AND logic).
  • Conversion example: sigma convert -t splunk rule.yml outputs Splunk SPL syntax.

Snort, YARA, and Sigma Positioning

  • Snort acts on network packets (transport layer); YARA acts on file/memory content (endpoint layer); Sigma acts on SIEM log events (analysis layer).
  • YARA detects static features, primarily for malware family identification, and lacks real-time blocking capabilities.
  • Sigma's goal is rule portability: the same rule can be converted into different SIEM query syntaxes, avoiding vendor lock-in.

Runtime Application Self-Protection (RASP)

RASP (Runtime Application Self-Protection) is a security mechanism embedded within an application that intercepts malicious calls in real-time during execution, rather than blocking at the external traffic layer.

AspectWAFRASP
Protection LocationExternal to application (traffic layer)Internal to application (runtime)
VisibilityHTTP requests and responsesFunction calls, memory state, database queries
Bypass RiskCan be bypassed by Obfuscation or encryptionDifficult for attackers to bypass (hooks directly into Runtime)
False Positive CostMay block legitimate requestsMay interrupt normal application flow
DeploymentReverse Proxy / CDN pluginInjected into application as Agent or Library

RASP's core mechanism is hooking critical APIs (e.g., SQL queries, file system access, OS command execution) to perform context validation at the moment of the call:

  1. Attacker triggers SQL Injection Payload.
  2. RASP intercepts before SQL execution, comparing the query structure against expected templates.
  3. If the structure is abnormal (e.g., contains UNION SELECT), it terminates and logs immediately, without waiting for external detection.

RASP vs WAF vs IPS Protection Layers

  • IPS: Network layer, targets packet signatures, does not understand application semantics.
  • WAF: Application layer boundary, parses HTTP, still cannot see backend execution state.
  • RASP: Inside the application, hooks execution time directly, understands the full function call context.

These are not mutually exclusive; they can coexist in Defense in Depth: WAF filters known attack signatures → RASP blocks semantic-layer attacks.

AppLocker, WDAC, and UAC (Windows Application Control)

MechanismAppLockerUAC (User Account Control)
PurposeRestricts which applications can runRestricts applications from obtaining high privileges
Control LevelExecution policy (Whitelist / Blacklist)Privilege escalation consent (Consent Prompt)
BasisPublisher, Path, HashWhether the application requests an Administrator Token
ScopeEnterprise environment, centrally applied via GPOAll Windows users (enabled by default)
Bypass RiskLOLBins abusing whitelisted paths (e.g., %WINDIR%)Known UAC Bypass techniques (DLL hijacking, COM object abuse)

AppLocker Rule Types:

  • Publisher Rule: Based on digital signature publisher, product name, and file version; most flexible and hardest to forge.
  • Path Rule: Based on file or folder path; fast but bypassable via path obfuscation.
  • Hash Rule: Based on specific file hash; most precise but high maintenance cost (must be recalculated on update).
AppLocker Query and Test Commands
powershell
# Read local AppLocker policy
Get-AppLockerPolicy -Local

# Read currently effective AppLocker policy
Get-AppLockerPolicy -Effective

# Test if a specific program can run under current policy
Test-AppLockerPolicy `
  -PolicyObject (Get-AppLockerPolicy -Effective) `
  -Path C:\Windows\System32\notepad.exe `
  -User Everyone
  • Get-AppLockerPolicy -Local shows local GPO settings; -Effective shows the merged result.
  • Test-AppLockerPolicy is suitable for verifying whether an executable will be allowed or blocked before applying it formally.
  • UAC is not a whitelist tool; its focus is privilege escalation prompts, not replacing AppLocker.

AppLocker vs UAC Responsibility Boundaries

  • AppLocker = "Can this program run?" — Entry control.
  • UAC = "Can this program get the administrator key?" — Privilege escalation control.
  • Complementary: AppLocker prevents unauthorized programs from starting; UAC prevents started programs from self-escalating privileges.
  • SRP (Software Restriction Policies) is the predecessor to AppLocker; still supported but no longer recommended. AppLocker supports finer-grained rules and audit modes.

Secure Boot, Measured Boot, and the TPM Chain of Trust

Chain of Trust in the Boot Process

UEFI Firmware → Secure Boot verifies signature → Load Bootloader → Load OS Kernel → OS Startup
ComponentDescription
UEFI Secure BootBefore loading the bootloader, the firmware verifies whether its digital signature is in the allowed list (db), rejecting unsigned or invalid code.
Measured BootThe hash values of components at each boot stage are recorded into the TPM's PCRs for verification via Remote Attestation.
TPM (Trusted Platform Module)A hardware security module that stores platform measurements (PCRs, Platform Configuration Registers) and encryption keys.
  • Defense Goal: Prevent Bootkits/Rootkits from tampering with the boot process before the OS loads.
  • TPM Version: TPM 2.0 is the current standard (mandatory for Windows 11) and supports more encryption algorithms (SHA-256, ECC).
  • BitLocker Integration: Windows BitLocker seals disk encryption keys within the TPM and binds them to the PCR measurements taken at boot. The key is automatically unsealed only if the "original machine + boot process remains untampered" condition is met. If the hard drive is moved to another machine, the TPM differs and the PCR values will not match, preventing the key from being unsealed and leaving the data as encrypted ciphertext. If the boot process is tampered with (e.g., a Rootkit is injected), the PCR values change, and the TPM will similarly refuse to release the key.
  • Risk: If an attacker obtains a maliciously signed, legitimate bootloader (e.g., BlackLotus UEFI Bootkit), Secure Boot may be bypassed, requiring firmware updates to revoke the compromised signatures.
Windows / Linux Secure Boot and TPM Check Commands
powershell
# Windows: Check if Secure Boot is enabled
Confirm-SecureBootUEFI

# Windows: View TPM status
Get-Tpm
bash
# Linux: View Secure Boot status
mokutil --sb-state

# Linux: List the allowed list in the Secure Boot database
mokutil --db
  • Confirm-SecureBootUEFI returns True / False; it will report as unsupported on non-UEFI platforms.
  • Get-Tpm allows for a quick check of statuses such as TpmPresent, TpmReady, and TpmEnabled.
  • mokutil --sb-state is a common way to quickly check Secure Boot on Linux.

Differences Between Secure Boot, Trusted Boot, and Measured Boot

MechanismActionPurposeBlocks Unauthorized Boot
Secure BootVerifies the digital signature of each boot component, rejects unsigned codePrevents unauthorized Bootloaders/Drivers from executing✅ Yes
Trusted BootAfter Secure Boot, verifies signatures of the Windows Kernel, Boot Drivers, and system filesExtends Secure Boot protection to the OS kernel level✅ Yes
Measured BootRecords the hash of each boot component to the TPM for post-boot or remote verificationProvides evidence of boot integrity, does not block boot❌ No (Records only)
  • Secure Boot protects the stage from UEFI firmware to the bootloader.
  • Trusted Boot continues from Secure Boot, protecting the Windows Kernel and Boot Driver loading stages (signature verification performed by the Windows Boot Manager).
  • Measured Boot spans the entire boot process but only "records" without "blocking." Recorded data can be used via Remote Attestation to allow a remote server to determine if the device is trustworthy.
  • The three are complementary: Secure Boot blocks unsigned code → Trusted Boot extends protection to the OS → Measured Boot provides verifiable evidence of trust.

WAF Rule Types and Deployment Modes

As listed in the Firewall Type Comparison Table, WAF is an L7 defense. This section supplements rule design and deployment architecture.

AspectDescription
Positive Model (Allowlist)Only allows requests matching predefined patterns; high security but strict configuration, suitable for scenarios with fixed structures like API Gateways.
Negative Model (Denylist)Blocks known malicious patterns (e.g., OWASP Core Rule Set, CRS); easy to deploy but may miss unknown attacks.
Hybrid ModelCombines positive and negative models; uses Denylist to block known attacks, then uses Allowlist to restrict the scope of legitimate requests.

Deployment Modes:

Deployment ModeEnglishDescription
Reverse ProxyReverse ProxyWAF acts as a proxy, receiving all traffic before forwarding it to the backend; can fully parse, modify, and cache requests. The most common deployment method.
Transparent BridgeTransparent BridgeDeployed as an L2 Bridge; requires no changes to network architecture or IP configuration.
Cloud WAFCloud WAFProvided by CDN / Cloud service providers (e.g., AWS WAF, Cloudflare WAF, Azure WAF); no need for self-built hardware, suitable for rapid deployment.

Common WAF Products

  • Open Source: ModSecurity (with OWASP CRS), Coraza.
  • Commercial: F5 Advanced WAF, Imperva WAF.
  • Cloud Native: AWS WAF, Azure WAF, Cloudflare WAF, Google Cloud Armor.

SOC (Security Operations Center), SIEM, and SOAR

SIEM Architecture:

Diagram
AspectSIEMSOAR
Full NameSecurity Information and Event ManagementSecurity Orchestration, Automation and Response
Core FunctionsLog aggregation, correlation analysis, threat detection, compliance reportingEvent auto-classification, Playbook automated response, cross-tool orchestration
Positioning"Detecting problems" — finding threats within massive logs"Handling problems" — automatically or semi-automatically disposing of detected threats
Typical IntegrationReceives various Log Sources, produces alerts and reportsReceives SIEM alerts, triggers Playbooks to automatically execute actions like blocking IPs, isolating hosts, or notifying on-call personnel
Representative ProductsSplunk, IBM QRadar, Microsoft Sentinel, Elastic SIEMSplunk SOAR, Palo Alto XSOAR, IBM Resilient

Collaboration Between SIEM and SOAR

  • SIEM = Monitor, responsible for seeing the problem.
  • SOAR = Automated Security Guard, responsible for handling the problem.
  • The two are usually used together: SIEM generates an alert → SOAR automatically responds according to a Playbook → Reduces manual workload for SOC personnel.

Playbook vs. Runbook

AspectPlaybookRunbook
DefinitionStrategic guidance document for incident response, describing "what to do when facing a certain type of event"Execution manual with specific operational steps, describing "how to execute each step"
Abstraction LevelHigh (Process and decision logic)Low (Commands and operations that can be followed directly)
Example"Ransomware Incident Playbook": Defines notification process, escalation criteria, decision tree"Isolate Infected Host Runbook": Log in to firewall → execute specific rules → verify isolation
UsersCSIRT Managers, Security ManagersSOC Analysts, Operations Engineers

One Playbook usually corresponds to multiple Runbooks; SOAR platforms can execute Playbooks automatically, reducing manual intervention time.

Red Team / Blue Team / Purple Team:

In security exercises, teams are divided by function into different colors, simulating attack and defense roles and providing feedback to each other to improve overall defensive capabilities.

TeamFunctionWork Content
Red TeamAttackerUses real attacker TTPs (Tactics, Techniques, Procedures) to launch simulated attacks against the target organization to find defensive gaps. Often designs attack chains based on the MITRE ATT&CK framework.
Blue TeamDefenderResponsible for monitoring, detecting, and responding to attacks. The SOC is the core operational unit of the Blue Team; tools include SIEM, IDS/IPS, and EDR.
Purple TeamCollaboratorNot an independent permanent team, but an operational mode: The Red Team shares attack paths and results with the Blue Team in real-time, and the Blue Team synchronizes adjustments to detection rules and response processes, forming a closed-loop improvement.

If the Red Team and Blue Team work in silos, reports remain just reports and defenses remain static after the exercise, yielding limited improvement. The core value of the Purple Team mode is "letting attack discovery directly drive defensive improvement," shortening the time gap between vulnerability discovery and patching detection capabilities.

Active Directory Attack Path Analysis:

In large enterprise Active Directory environments, the permission relationships between accounts, groups, and computer objects are complex and difficult to map manually. In Red Team exercises, attackers use Graph Theory algorithms, treating AD objects as Nodes and permission delegation relationships as Directed Edges, then using shortest path algorithms (BFS/Dijkstra) to find the minimal privilege escalation chain from a standard user to Domain Admin.

ToolDescription
BloodHoundOpen-source AD attack path visualization tool; uses Neo4j graph database to store AD object relationships and Cypher query language to find the shortest escalation path. Representative query: "Which standard users can reach Domain Admins the fastest?"
SharpHound (Collector)BloodHound's data collection component; executes within the target domain to capture AD objects (accounts, groups, GPOs, ACLs) and outputs JSON for BloodHound import.
AzureHoundBloodHound's Entra ID (Azure AD) extension; supports attack path analysis for cloud and hybrid environments.

Value of BloodHound for the Blue Team

BloodHound is not just a Red Team tool; the Blue Team can also proactively scan their own environment for attack paths and fix them before attackers can exploit them. Common applications:

  • Identify accounts with excessive delegation privileges (Kerberoastable / AS-REP Roastable).
  • Find the shortest path to Domain Admin and prioritize clearing high-risk "bridge node" accounts.
  • Verify which accounts possess the DS-Replication-Get-Changes-All permission required for DCSync attacks.

SOC Tier Model:

Diagram
TierRoleWork Content
Tier 1Alert Triage AnalystMonitors SIEM alerts, performs initial classification and eliminates False Positives, escalates confirmed incidents to Tier 2.
Tier 2Incident ResponderInvestigates incidents in depth, performs log correlation analysis, determines attack scope, and executes initial containment.
Tier 3Threat Hunter / Forensic AnalystProactively hunts for threats not caught by alerts, performs digital forensics and root cause analysis, produces threat intelligence. See Threat Hunting.
ManagerSOC ManagerStrategic planning, KPI tracking (MTTD / MTTR), team management, and process optimization.

EDR / XDR / MDR Comparison Table

AspectEDRXDRMDR
Full NameEndpoint Detection and ResponseExtended Detection and ResponseManaged Detection and Response
Protection ScopeEndpoints (PC, Server)Endpoints + Network + Cloud + Email + Identity and other data sourcesSame as EDR/XDR, but managed by an external vendor
Core ValueEndpoint behavior detection, Threat Hunting, incident responseCross-data source correlation analysis, reduces Alert FatigueSolves the problem of enterprise lack of security personnel
Data IntegrationEndpoint telemetry data onlyIntegrates multi-source telemetry into a unified platformDepends on the service provider, usually integrates EDR or XDR
Operational ModeEnterprise self-operatedEnterprise self-operatedOutsourced to a security service provider (MSSP), 7×24 monitoring
Representative ProductsCrowdStrike Falcon, Microsoft Defender for Endpoint, Carbon BlackMicrosoft 365 Defender, Palo Alto Cortex XDR, Trend Micro Vision OneCrowdStrike Falcon Complete, Arctic Wolf

EDR / XDR / MDR Positioning Differences

  • EDR = Endpoint "dashcam," records all behavior on the endpoint for analysis.
  • XDR = Extends the dashcam to network, cloud, and email for cross-domain correlation analysis.
  • MDR = Hands the dashcam over to a professional fleet management company to manage.
  • The three are not mutually exclusive: Enterprises can use an XDR platform + MDR managed service.

eBPF (extended Berkeley Packet Filter)

eBPF (extended Berkeley Packet Filter) allows for the execution of sandboxed, user-defined programs within the Linux kernel without modifying kernel source code or loading kernel modules. Programs are verified for safety by the kernel's built-in Verifier upon loading; only verified programs can execute.

Dual-use Applications of eBPF in Security:

DirectionApplicationRepresentative Tools
Defense (Observation & Protection)Captures system calls (syscalls), network packets, and process behavior, achieving real-time visibility at the kernel level with extremely low latencyFalco (Runtime threat detection), Cilium (K8s network security), Tetragon (Security observability)
Defense (Network Filtering)Drops malicious packets directly at the network card driver layer (XDP, eXpress Data Path), performance is far higher than iptablesCloudflare DDoS protection, Cilium NetworkPolicy
Attack (eBPF Rootkit)Hooks kernel functions with eBPF programs to hide processes, network connections, and files; does not require traditional kernel modules (LKM), making it harder to detectBoopkit, ebpfkit

Comparison with Traditional Methods:

Traditional Kernel Module (LKM)eBPF
Security IsolationKernel module crashes lead directly to system crashesSandboxed execution; Verifier prevents infinite loops and memory out-of-bounds
Deployment BarrierRequires recompilation or signing of kernel modulesDynamically loaded at runtime, no reboot required
ObservabilityLimitedCan hook any kernel function, extremely high visibility
eBPF Rootkit DetectionMonitor bpf() system calls; use bpftool to list loaded eBPF programs; check for unexpected program attachment points (Hook Points)

Relationship Between EDR and eBPF

Modern Linux EDR tools (e.g., Falco, Tetragon, CrowdStrike Falcon on Linux) heavily adopt eBPF as the data collection layer, replacing the need to load kernel modules. The reason is that eBPF balances "low overhead, high visibility, and no impact on system stability." eBPF enables EDR to track system calls like exec, open, and connect at the kernel level with lower latency than user-space auditd.

Deception Technology

TechnologyEnglishDescription
HoneypotHoneypotSimulates a single vulnerable system (e.g., fake SSH Server, fake database) to lure attackers into interacting, thereby collecting attack techniques and IOCs.
HoneynetHoneynetA simulated network environment composed of multiple Honeypots, used to observe lateral movement behavior of attackers within the network.
Honey TokenFake accounts, API Keys, documents, or DNS records; triggers an alert as soon as they are accessed or used.
Deception PlatformEnterprise-grade deception defense platform (e.g., Attivo Networks, Illusive Networks), automatically deploys decoys throughout the network and integrates alerts with SIEM/SOAR.

Honeypot Classification

  • Low-interaction: Only simulates service responses (e.g., Honeyd); simple to deploy but collects limited intelligence.
  • High-interaction: Provides a real operating system and service environment; can observe attacker behavior in depth, but carries higher risk (may be used as a jump host).
  • The positioning of a Honeypot is intelligence collection and delaying attackers, not active blocking; active interception relies on firewalls and IPS. Treating a Honeypot as a defensive line is a misuse; its core value lies in letting the defender "see how the attacker moves."

Sandboxing Applications

The general concept of Sandbox is already listed in the Common Security Defense Technology Comparison Table; the following supplements implementations at various levels.

Sandbox TypeDescriptionExamples
Browser SandboxRestricts the web rendering engine and plugins to isolated processes; even if exploited, they cannot access operating system resources.Chromium multi-process architecture, Firefox Fission
Application SandboxRestricts the file system, network, and IPC access scope of applications at the OS level.macOS App Sandbox, Windows AppContainer, Linux Flatpak/Snap
Malware Analysis SandboxExecutes suspicious files in a controlled virtual environment to observe their behavior (file operations, network connections, Registry modifications).Cuckoo Sandbox (Open source), Joe Sandbox, ANY.RUN
Container SandboxUses Linux Namespaces and cgroups to isolate process resources, combined with Seccomp to restrict system calls.Docker, gVisor (User-space Kernel), Kata Containers (Micro VM)

DLP (Data Loss Prevention)

DLP identifies sensitive data through detection mechanisms and controls data flow based on deployment location.

Common Detection Mechanisms

Detection MechanismPrincipleTypical Example
Keyword / Regex MatchingMatches text patterns, triggers default rulesDetect "Confidential," credit card number format \d{4}-\d{4}-\d{4}-\d{4}
Data FingerprintingCalculates fingerprint hashes for confidential documents, detects partial or full copiesLeak detection for structured documents like contracts, source code, design blueprints
Machine Learning ClassificationTrains models to automatically identify sensitive content categoriesAutomatically tags unstructured documents containing PII

Deployment Types

DLP TypeMonitoring LocationProtection Scenario
Endpoint DLPFile operations, clipboard, USB, printing on user devicesPrevents employees from copying confidential files to USB drives or uploading them to personal cloud storage.
Network DLPEmail, HTTP/HTTPS, FTP traffic at network gatewaysDetects and intercepts sensitive data leaked via Email attachments or Web uploads.
Cloud DLPFiles and messages in SaaS applications (e.g., Microsoft 365, Google Workspace)Scans sensitive data in cloud storage (e.g., ID numbers, credit card numbers), applies classification labels and encryption.
Diagram

DLP Deployment Considerations

  • DLP must be paired with Data Classification to clearly define detection rules corresponding to each sensitivity level to function effectively.
  • Network DLP cannot directly inspect content in encrypted traffic (HTTPS); it must be paired with SSL/TLS decryption to perform content scanning.

Email Security Gateway / Anti-Spam

Email Security Gateways are deployed in front of mail servers, providing multiple layers of protection against different threat levels.

Defense LayerTechnologyDescription
Connection LayerSPF / DKIM / DMARCVerifies sender identity, prevents Email Spoofing.
Content LayerAnti-Spam FilterBayesian Filter, keyword rules, sender reputation scoring, filters spam.
Threat LayerAnti-Malware / SandboxingScans attachments for malware, sends suspicious files to a sandbox for detonation analysis.
Link LayerURL Rewriting / Time-of-Click ProtectionRewrites URLs in emails to secure gateway links; scans the target webpage in real-time when the user clicks to check if it is a phishing or malicious site.

The combination of SPF / DKIM / DMARC forms a complete defensive line for email sender identity verification:

TechnologyFull NameVerification MethodFunction
SPFSender Policy FrameworkDNS TXT record lists authorized IP list; receiver verifies if source IP is in the listPrevents spoofing source IP to send emails
DKIMDomainKeys Identified MailSender adds digital signature to email header and content; receiver verifies with public key on DNSEnsures email has not been tampered with and was indeed sent by the claimed domain
DMARCDomain-based Message Authentication, Reporting and ConformanceDefines policy (none / quarantine / reject) when SPF/DKIM verification fails, provides reporting mechanismIntegrates SPF and DKIM results, unifies decision-making, and receives violation reports

Division of Labor for SPF, DKIM, and DMARC

  • SPF only verifies source IP, DKIM only verifies signature; both are independent. DMARC is the integration layer, defining "how to handle the email if SPF or DKIM fails."
  • All three rely on DNS records; corresponding TXT records must be set in the sending domain's DNS to take effect.

Patch Management

StageActivityDescription
1. InventoryAsset InventoryEstablish a complete software/hardware inventory, confirm version and patch status of each system.
2. AssessVulnerability Scan + Severity RatingPrioritize patching based on CVSS scores and business impact.
3. TestVerify in Test EnvironmentConfirm that patches do not cause compatibility issues or service interruptions.
4. DeployPhased RolloutPilot group → Full deployment. Automate using tools like WSUS, SCCM, Ansible, etc.
5. VerifyConfirm Application StatusRe-scan to confirm vulnerability is patched, record exceptions (compensating controls required for unpatchable systems).
Diagram

Patch Management Considerations

  • Emergency Patch: For vulnerabilities with CVSS 9.0+ or existing public exploits, shorten the test cycle and prioritize deployment.
  • Virtual Patching: Before formal patching, use WAF / IPS rules to block attack traffic targeting known vulnerabilities.
  • Risk of Patch Delay: Statistics show that most security incidents exploit known vulnerabilities that have been public for over 30 days, not Zero-days.

MTTP (Mean Time To Patch)

Measures the average time from vulnerability disclosure (CVE announcement / vendor disclosure) to completion of patch deployment; it is a key KPI for vulnerability and patch management.

Risk LevelIndustry Recommended MTTP
CVSS 9.0+ (Critical)< 7 days
CVSS 7.0–8.9 (High)< 30 days
CVSS 4.0–6.9 (Medium)< 90 days
CVSS < 4.0 (Low)Per schedule
  • Difference from Incident Response Metrics: MTTD / MTTA / MTTR measure detection and response speed "after an incident occurs"; MTTP measures preventive patching speed "before an incident occurs." They are metrics for different stages.
  • Key to Reducing MTTP: Automated scanning (e.g., Tenable, Qualys), standardized patch testing environments, and Emergency Change Processes that bypass some review steps.
  • Linked to SLA: Mature organizations write MTTP into internal SLAs or compliance requirements (e.g., PCI-DSS requires Critical vulnerabilities to be patched within 30 days).
Windows / Linux Patch Inventory and Update Commands
powershell
# Windows: View installed Hotfixes
Get-HotFix

# Windows: View recently installed patches
Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 10
bash
# Debian / Ubuntu: Sync package index and view upgradable packages
sudo apt update
apt list --upgradable
sudo apt upgrade

# RHEL / Rocky / AlmaLinux: View upgradable packages and security advisories
sudo dnf check-update
sudo dnf updateinfo list security
sudo dnf upgrade --security
  • The common practice on Windows is to use Get-HotFix to inventory the current status, then hand it over to WSUS, SCCM, Intune, or enterprise processes for update deployment.
  • apt list --upgradable is suitable for inventory; apt upgrade is the actual upgrade.
  • dnf updateinfo list security allows viewing security advisories first; dnf upgrade --security means applying security patches only.

Threat Intelligence Platform (TIP)

AspectDescription
DefinitionA platform for centralized management, analysis, and sharing of threat intelligence, integrating IOCs, TTPs (Tactics, Techniques, and Procedures), and vulnerability information into actionable intelligence.
Intelligence SourcesOSINT (Open Source Intelligence), commercial intelligence subscriptions (e.g., Recorded Future, Mandiant), ISAC (Information Sharing and Analysis Center), and self-collected honeypot data.
Core FunctionsIOC management and lifecycle tracking, intelligence correlation analysis, automated blocking via SIEM/SOAR/EDR integration, and standardized format exchange via STIX/TAXII.
Representative ProductsMISP (Open source), ThreatConnect, Anomali ThreatStream.

UEBA (User and Entity Behavior Analytics)

AspectDescription
Core PrincipleUses machine learning to establish a normal behavior baseline for users and devices; deviations from the baseline generate risk scores.
Detection ScenariosInsider Threat: Abnormal large-scale data downloads, logins outside working hours. Account Compromise: Same account logging in from different geographic locations within a short time. Lateral Movement: An account suddenly accessing systems it has never touched before.
Difference from SIEMSIEM alerts based on rules (Rule-based); UEBA alerts based on behavior baseline deviations (Baseline-based), making it better at detecting "legitimate accounts doing abnormal things."
Representative ProductsMicrosoft Sentinel UEBA, Exabeam, Splunk UBA.

NTA (Network Traffic Analysis)

AspectDescription
DefinitionPerforms deep analysis on network traffic to detect abnormal patterns (e.g., C2 Beaconing, data exfiltration, lateral movement).
Difference from IDS/IPSIDS/IPS focuses on signature matching; NTA focuses on traffic statistics and behavior analysis, capable of detecting abnormal patterns within encrypted traffic (without decryption).
Core TechnologyNetFlow / sFlow analysis, packet Metadata analysis, machine learning to establish traffic baselines.
Representative ProductsDarktrace, Vectra AI, Cisco Secure Network Analytics.

Secure DNS

ProtocolFull NameTransmission MethodDefault PortDescription
DoHDNS over HTTPSEncapsulates DNS queries in HTTPS requests443Mixed with general HTTPS traffic, difficult for man-in-the-middle to identify or block DNS queries.
DoTDNS over TLSEncrypts DNS queries using TLS853Uses a dedicated port, easier for firewalls to identify and control.

Detection Differences Between DoH and DoT

  • DoT: Uses dedicated port 853; firewalls only need to block or monitor this port to identify and control it; low detection barrier.
  • DoH: Uses port 443, shared with general HTTPS; appearance is indistinguishable from normal web requests; even with DPI (Deep Packet Inspection), TLS encryption blocks content, making it impossible to directly see that it is a DNS query.
  • Common means of detecting DoH: Track IPs / domains of known DoH providers (e.g., 1.1.1.1, 8.8.8.8), or indirectly identify through behavior analysis (small, fixed-frequency HTTPS requests). If an attacker sets up their own DoH server, the above methods will fail.
  • Malware therefore prefers using DoH for C2 communication or DNS Tunneling, as traffic is mixed into normal HTTPS, making it harder for security equipment to discover.

Role of DNS in Security Defense

  • DNS Sinkhole: Directs DNS resolution of known malicious domains to harmless IPs (e.g., 127.0.0.1), preventing malware from connecting to C2 servers.
  • DNS Filtering: Filters malicious or inappropriate websites at the DNS layer (e.g., Cisco Umbrella, Quad9).
  • Traditional DNS (Port 53) transmits in plaintext, making it easy to eavesdrop or tamper with (DNS Spoofing); DoH/DoT can solve this problem.

Linux / Windows Defense Tools Comparison Table

Defense CategoryLinux ToolsWindows ToolsDescription
Host Firewalliptables / nftablesWindows Defender FirewallLinux implements packet filtering via the Netfilter framework; Windows implements it via the WFP (Windows Filtering Platform) underlying framework, with Windows Defender Firewall on top. nftables is the successor to iptables, with unified syntax and better performance.
Endpoint ProtectionClamAV (Anti-Virus) / OSSEC (HIDS)Windows Defender Antivirus / AMSIClamAV is an open-source antivirus engine, suitable for Mail Gateway scanning. AMSI (Antimalware Scan Interface) allows script engines (PowerShell, VBScript) to send content to the antivirus engine for inspection.
Log Centralizationrsyslog / journald → Forward to SIEMWindows Event Forwarding (WEF) → Forward to SIEMrsyslog supports TCP/TLS forwarding; WEF forwards event logs to a Collector via WinRM.
Vulnerability ScanOpenVAS (Greenbone) / NessusNessus / MBSA (Discontinued)OpenVAS is an open-source vulnerability scanner maintained by Greenbone. MBSA (Microsoft Baseline Security Analyzer) was discontinued in 2018; it is recommended to switch to Microsoft Defender Vulnerability Management.
Intrusion DetectionSnort / Suricata / OSSECWindows Defender for Endpoint (EDR)Snort/Suricata are network-based IDS/IPS; OSSEC/Wazuh are host-based HIDS.
File Integrity MonitoringAIDE / Tripwire / OSSEC SyscheckWindows FIM (Azure Defender)Monitors changes in hash values of critical system files to detect unauthorized modifications.
Brute Force Defensefail2ban / DenyHostsAccount Lockout Policy (GPO)fail2ban monitors logs and automatically blocks source IPs; Windows sets account lockout thresholds via Group Policy.
Common Defense Tool Check Commands
powershell
# Windows: View status of each firewall Profile
netsh advfirewall show allprofiles

# Windows: View current status of Microsoft Defender
Get-MpComputerStatus

# Windows: Update Defender signatures and perform a quick scan
Update-MpSignature
Start-MpScan -ScanType QuickScan
  • Linux iptables / nftables rule viewing and persistence are unified in the previous iptables / nftables firewall rule examples block to avoid repeating the same set of commands in different chapters.
  • Get-MpComputerStatus can check if Defender is enabled and if signatures are expired.
  • Update-MpSignature and Start-MpScan -ScanType QuickScan are very suitable for basic health checks.

Cross-Platform Security Mechanism Comparison Table

FeaturePurposeWindowsLinux
Auditing/LoggingRecords system events for post-incident investigation and forensicsEvent Log (System/Application event logs)
Sysmon (Advanced behavior monitoring, records process creation, network connections)
Syslog (Traditional Unix system logging protocol)
journald (systemd structured logging, supports query filtering)
auditd (Kernel-level system call auditing)
Access ControlControls the scope of resources accessible by users or programsNTFS ACL (File-level granular permissions)
GPO (Centralized Group Policy application)
rwx (Traditional Unix three-tier permissions)
POSIX ACL (Extends beyond rwx limits, allows specific permissions for individual users or groups)
SELinux / AppArmor (Mandatory Access Control layer)
FirewallFilters incoming/outgoing network traffic, blocks unauthorized connectionsWindows Defender Firewall (Built-in host firewall)iptables (Traditional kernel packet filtering)
nftables (Next-generation replacement)
firewalld (Dynamic management interface, supports zones)
Security BaselineProvides a standard checklist for system security configurationsSecurity Baseline (Official Microsoft baseline settings)
GPO (Application mechanism)
CIS Benchmark (Cross-platform security configuration baseline)
OpenSCAP (Automated compliance scanning)
Lynis (Local security auditing tool)
Mandatory Access ControlEnforces restrictions on program access behavior on top of traditional permissions, even if high privileges are obtainedMandatory Integrity Control (MIC) (Restricts inter-process access based on integrity levels)SELinux (Policy-based mandatory access, default on Red Hat family)
AppArmor (Path-based profile control, default on Ubuntu family)
Application WhitelistingAllows only approved programs to execute, blocks unknown or malicious programsAppLocker (Rule-based whitelisting)
WDAC (Kernel-level enforcement, harder to bypass)
fapolicyd (Rule-based application execution control)
Linux File Permission Commands
bash
# View permissions
ls -la /etc/passwd

# Set permissions: owner read/write, group read, others no access
chmod 640 sensitive.conf

# Change owner and group
chown root:admin sensitive.conf

# View POSIX ACL
getfacl /etc/shadow

Defense in Depth

Diagram

Defense in Depth vs. Zero Trust

  • Defense in Depth emphasizes multi-layered protection; even if one layer is breached, other lines of defense remain.
  • Zero Trust emphasizes "never trust, always verify," assuming that any location could be compromised.
  • The two are complementary: Defense in Depth provides a structured layered framework, while Zero Trust provides the core principles of access control. In SSDLC and DevSecOps workflows, security should be integrated into every layer starting from the design phase.

C# Security Implementation Examples

Content Security Policy (CSP) Header Configuration
csharp
// Program.cs — ASP.NET Core Middleware to set CSP Header
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();

app.Use(async (context, next) => {
    context.Response.Headers.Append(
        "Content-Security-Policy",
        "default-src 'self'; "
        + "script-src 'self'; "
        + "style-src 'self' 'unsafe-inline'; "
        + "img-src 'self' data:; "
        + "font-src 'self'; "
        + "connect-src 'self'; "
        + "frame-ancestors 'none'; "
        + "base-uri 'self'; "
        + "form-action 'self'"
    );

    // Set other security headers simultaneously
    context.Response.Headers.Append("X-Content-Type-Options", "nosniff");
    context.Response.Headers.Append("X-Frame-Options", "DENY");
    context.Response.Headers.Append("Referrer-Policy", "strict-origin-when-cross-origin");

    await next();
});

app.MapGet("/", () => "Hello, Secure World!");
app.Run();
Rate Limiting Middleware (Built-in for .NET 7+)
csharp
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

// Register Rate Limiter service
builder.Services.AddRateLimiter(options => {
    // Fixed Window: Max 100 requests every 60 seconds
    options.AddFixedWindowLimiter("fixed", config => {
        config.PermitLimit = 100;
        config.Window = TimeSpan.FromSeconds(60);
        config.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
        config.QueueLimit = 10;
    });

    // Sliding Window: Smoother traffic control
    options.AddSlidingWindowLimiter("sliding", config => {
        config.PermitLimit = 100;
        config.Window = TimeSpan.FromSeconds(60);
        config.SegmentsPerWindow = 6; // One segment every 10 seconds
        config.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
        config.QueueLimit = 10;
    });

    // Response when globally rejected
    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
    options.OnRejected = async (context, cancellationToken) => {
        context.HttpContext.Response.ContentType = "application/json";
        await context.HttpContext.Response.WriteAsync(
            """{"error": "Too many requests. Please try again later."}""",
            cancellationToken
        );
    };
});

WebApplication app = builder.Build();
app.UseRateLimiter();

// Apply Rate Limiter to specific endpoint
app.MapGet("/api/data", () => Results.Ok(new { Message = "OK" }))
    .RequireRateLimiting("fixed");

app.Run();
IP Whitelist / Blacklist Middleware
csharp
using System.Net;
using Microsoft.Extensions.Options;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

// Read allowed IP list from configuration file
builder.Services.Configure<IpFilterOptions>(
    builder.Configuration.GetSection("IpFilter")
);

WebApplication app = builder.Build();
app.UseMiddleware<IpFilterMiddleware>();
app.MapGet("/", () => "Access granted.");
app.Run();

/// <summary>
/// IP filtering configuration options.
/// </summary>
public class IpFilterOptions {
    /// <summary>
    /// Gets or sets the whitelist of allowed IP addresses.
    /// </summary>
    public List<string> Whitelist { get; set; } = [];

    /// <summary>
    /// Gets or sets the blacklist of blocked IP addresses.
    /// </summary>
    public List<string> Blacklist { get; set; } = [];
}

/// <summary>
/// Filters requests based on client IP against whitelist and blacklist.
/// </summary>
public class IpFilterMiddleware {
    private readonly RequestDelegate next;
    private readonly IpFilterOptions options;
    private readonly ILogger<IpFilterMiddleware> logger;

    /// <summary>
    /// Initializes a new instance of the <see cref="IpFilterMiddleware"/> class.
    /// </summary>
    public IpFilterMiddleware(
        RequestDelegate next,
        IOptions<IpFilterOptions> options,
        ILogger<IpFilterMiddleware> logger
    ) {
        this.next = next;
        this.options = options.Value;
        this.logger = logger;
    }

    /// <summary>
    /// Processes the HTTP request and applies IP filtering.
    /// </summary>
    public async Task InvokeAsync(HttpContext context) {
        IPAddress? remoteIp = context.Connection.RemoteIpAddress;

        if (remoteIp is null) {
            context.Response.StatusCode = StatusCodes.Status403Forbidden;
            return;
        }

        string clientIp = remoteIp.MapToIPv4().ToString();

        // Blacklist priority: Deny immediately if in blacklist
        if (options.Blacklist.Contains(clientIp)) {
            logger.LogWarning("Blocked request from blacklisted IP: {ClientIp}", clientIp);
            context.Response.StatusCode = StatusCodes.Status403Forbidden;
            await context.Response.WriteAsync("Access denied.");
            return;
        }

        // If Whitelist is configured and IP is not in whitelist, deny
        if (options.Whitelist.Count > 0 && !options.Whitelist.Contains(clientIp)) {
            logger.LogWarning("Blocked request from non-whitelisted IP: {ClientIp}", clientIp);
            context.Response.StatusCode = StatusCodes.Status403Forbidden;
            await context.Response.WriteAsync("Access denied.");
            return;
        }

        await next(context);
    }
}

appsettings.json configuration example:

json
{
  "IpFilter": {
    "Whitelist": ["127.0.0.1", "192.168.1.100"],
    "Blacklist": ["10.0.0.99"]
  }
}

Defense Tool Configuration Examples (Linux)

fail2ban Configuration Example (SSH Brute Force Protection)
bash
# Install fail2ban (Debian/Ubuntu)
sudo apt-get install -y fail2ban

# Create local configuration (do not modify jail.conf directly)
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
ini
# /etc/fail2ban/jail.local — SSH protection settings
[sshd]
enabled  = true
port     = ssh
filter   = sshd
logpath  = /var/log/auth.log
maxretry = 5
findtime = 600
bantime  = 3600
action   = iptables-multiport[name=sshd, port="ssh", protocol=tcp]
bash
# Enable and check status
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
sudo fail2ban-client status sshd
OSSEC / Wazuh Agent Installation Commands
bash
# Wazuh Agent installation (Debian/Ubuntu) — Wazuh is an active fork of OSSEC
# Install required packages if missing
sudo apt-get install -y gnupg apt-transport-https

# Import official GPG Key
curl -s https://packages.wazuh.com/key/GPG-KEY-WAZUH | \
  gpg --no-default-keyring \
  --keyring gnupg-ring:/usr/share/keyrings/wazuh.gpg --import
sudo chmod 644 /usr/share/keyrings/wazuh.gpg

# Add official package repository
echo "deb [signed-by=/usr/share/keyrings/wazuh.gpg] \
  https://packages.wazuh.com/4.x/apt/ stable main" | \
  sudo tee /etc/apt/sources.list.d/wazuh.list

sudo apt-get update

# Install and specify Wazuh Manager address during installation
sudo env WAZUH_MANAGER="192.168.1.10" apt-get install -y wazuh-agent

# Start Agent
sudo systemctl daemon-reload
sudo systemctl enable wazuh-agent
sudo systemctl start wazuh-agent
Snort / Suricata Rule Example
bash
# Suricata installation (Debian/Ubuntu)
sudo apt-get install -y suricata

# Enable community rules
sudo suricata-update
yaml
# /etc/suricata/suricata.yaml (Key configuration excerpt)
af-packet:
  - interface: eth0
    cluster-id: 99
    cluster-type: cluster_flow

default-rule-path: /var/lib/suricata/rules
rule-files:
  - suricata.rules
text
# Custom rule example (/var/lib/suricata/rules/local.rules)

# Detect SQL Injection attempts
alert http any any -> $HOME_NET any ( \
  msg:"Possible SQL Injection attempt"; \
  flow:to_server,established; \
  content:"UNION"; nocase; \
  content:"SELECT"; nocase; \
  sid:1000001; rev:1; \
)

# Detect SSH brute force
alert ssh any any -> $HOME_NET 22 ( \
  msg:"SSH brute force attempt"; \
  flow:to_server; \
  threshold:type both, track by_src, count 5, seconds 60; \
  sid:1000002; rev:1; \
)
ClamAV Scanning Commands
bash
# Install ClamAV (Debian/Ubuntu)
sudo apt-get install -y clamav clamav-daemon

# Update virus database
sudo systemctl stop clamav-freshclam
sudo freshclam
sudo systemctl start clamav-freshclam

# Scan specified directory (report only, do not delete)
clamscan -r /home --log=/var/log/clamav/scan.log

# Scan and remove infected files
clamscan -r /home --remove --log=/var/log/clamav/scan.log

# Scan and move infected files to a specified directory
clamscan -r /home --move=/var/quarantine --log=/var/log/clamav/scan.log

# Scheduled scan (add to crontab): Full system scan every day at 2 AM
# 0 2 * * * clamscan -r / --exclude-dir="^/sys|^/proc|^/dev" \
#   --log=/var/log/clamav/daily.log

Identity and Access

Access Control Models Comparison Table

ModelFull NameControl OwnershipAuthorization LogicTypical Use Cases
DACDiscretionary Access ControlResource OwnerOwner decides who can access, can freely grant or revoke accessWindows NTFS file permissions, Linux chmod
MACMandatory Access ControlSystem/AdministratorEnforced based on data sensitivity (e.g., Top Secret/Secret/Sensitive) and user clearance; owner cannot adjustMilitary, government classified systems
RBACRole-Based Access ControlRole DefinitionUsers assigned to roles; roles correspond to a set of default permissionsEnterprise ERP, Cloud IAM (Identity and Access Management, e.g., AWS IAM Role)
ABACAttribute-Based Access ControlDynamic PolicyAuthorization calculated based on user attributes, resource attributes, and environment attributes (e.g., time, location)Zero Trust architecture, granular API access control
CBACClaim-Based Access ControlTrusted Identity Provider (IdP)Authorization based on claims in a Token (e.g., JWT); system does not manage roles directly, IdP issues claims, decoupling auth logic from identity verificationAzure AD, SAML federation, OIDC cross-org login
ReBACRelationship-Based Access ControlSubject-Resource RelationshipAuthorization based on the relationship between user and resource (owner, member, viewer)File sharing, social platforms (e.g., Google Drive sharing, SpiceDB)

Authorization Decision Source Diagram

Diagram

Core Concepts of Access Control Models

  • DAC = "I own this folder, I decide who can read it."
  • MAC = "Regardless of whether you are the owner, your clearance is insufficient." (The system decides)
  • RBAC = "Your position is Accountant, the system grants you Accountant role permissions."
  • ABAC = "You are a Taiwan employee + working hours + company network → Allow; if one condition fails → Deny."
  • CBAC = "Your JWT Token contains the role=admin claim, the IdP says you have it, so the system trusts it." (System does not maintain role mapping tables itself)
  • Flexibility (who can change, how to change): DAC (owner self-change) < RBAC (requires role reconfiguration) < ABAC (most flexible condition combinations).
  • Security Enforcement (can it be bypassed): MAC > DAC — MAC is enforced by the system, owners cannot delegate access rights themselves; DAC owners can.
  • Industry Practice: Windows AD uses RBAC (group-based authorization); AWS IAM uses ABAC (tag-attribute-based authorization); Linux file systems use DAC (file owners set rwx permissions).
  • Principle of Least Privilege (PoLP) Industry Practice: Database accounts are granted only SELECT/INSERT based on application needs, not DELETE/DROP; CI/CD Pipeline deployment accounts have permissions only for specific Kubernetes namespaces.

RBAC / ABAC / ReBAC Maintenance Costs

The authorization basis and use cases for the three are shown in the table above; the differences mainly lie in maintenance costs:

ModelMaintenance CostMain Consideration
RBACLow to MediumLow cost when roles are stable; prone to "role explosion" in large organizations
ABACMedium to HighPolicies written as multi-attribute combinations; complexity increases with conditions
ReBACMediumRelationship model is intuitive, but query performance of relationship graphs requires attention
  • Role Explosion: In large organizations, the permutations of department × system × environment (dev/test/prod) can lead to thousands of roles, making maintenance difficult. ABAC or ReBAC can mitigate this.
  • The core concept of ReBAC originates from Google's Zanzibar paper (2019) and is used by Google Drive, YouTube, etc., for large-scale permission management.

Common Violations of Least Privilege

Violation PatternDescriptionCorrection
God AccountDev/Ops share a single account with full administrator privilegesSplit accounts by responsibility, use PAM to manage privileged accounts.
Permission CreepOld permissions not revoked after employee transfers departmentsPerform regular Access Reviews / Recertification.
Overly Broad IAM PolicyCloud IAM uses * (wildcard) to grant permissions for all resources or actionsExplicitly list required Actions and Resources, use Policy Analyzer tools to detect overly broad permissions.
Shared Service AccountMultiple applications share the same service account, impossible to distinguish sourceAssign independent Service Accounts to each application (see Service Account Management).
Permanent AccessAdmin accounts hold high privileges 7x24, even when not neededAdopt JIT (Just-in-Time) Access, request only when needed, revoke after use.

Bell-LaPadula and Biba Security Models

These two models are the theoretical basis for MAC (Mandatory Access Control), establishing read/write rules for different security attributes:

ModelProtection GoalRule AbbreviationRule Description
Bell-LaPadulaConfidentialityNRU (No Read Up)Cannot read data at a higher level than self, prevents leakage of confidential info
Bell-LaPadulaConfidentialityNWD (No Write Down)Cannot write data to a lower level area, prevents high-level users from downgrading secrets
BibaIntegrityNRD (No Read Down)Cannot read data at a lower level than self, avoids contamination from unreliable sources
BibaIntegrityNWU (No Write Up)Cannot write to a higher level area, prevents low-trust data from contaminating high-trust areas

Bell-LaPadula and Biba Prohibition Direction Diagram

Dashed lines represent prohibited read/write directions.

Diagram

Comparison of Bell-LaPadula and Biba

  • Bell-LaPadula is the theoretical basis for military classification (e.g., Unclassified / Confidential / Secret / Top Secret).
  • The read/write rule directions of Bell-LaPadula and Biba are exactly opposite because their protection goals differ (confidentiality vs. integrity).
  • Both can be complementary: implementing both can balance confidentiality and integrity, but the cost of full implementation in practice is extremely high.

Authentication Factor Types Comparison Table

Factor TypeDescriptionCommon Examples
Knowledge Factor (Something You Know)Secrets memorized by the userPasswords, PINs, security question answers
Possession Factor (Something You Have)Physical or digital objects held by the userOTP (One-Time Password) hardware tokens, mobile Authenticator Apps, smart cards
Inherence Factor (Something You Are)Physiological or behavioral characteristicsFingerprints, facial recognition, iris scans, voiceprints
Location Factor (Somewhere You Are)Geographic location or network environmentIP range restrictions, Geo-fencing

Difference between MFA and 2FA

  • MFA (Multi-Factor Authentication) = Using 2 or more different types of factors simultaneously.
  • Same-type doesn't count: Entering password + answering security question = both are knowledge factors = not MFA.
  • 2FA ⊂ MFA; 2FA is the specific case of using only 2 factors.

Adaptive Authentication

Also known as Risk-based Authentication, it dynamically adjusts authentication requirements based on the risk level of the login context:

Risk SignalLow-Risk BehaviorHigh-Risk Behavior
LocationLogin from common locationLogin from a country never used before
DeviceLogin from registered deviceLogin from a brand new device
TimeLogin during normal working hoursLogin at 3 AM
Behavior PatternAccessing systems used normallyDownloading large amounts of sensitive data in a short time
NetworkLogin from corporate networkLogin from known malicious IP or Tor exit node

Operating Logic:

  • Low Risk → Password only (or passwordless).
  • Medium Risk → Trigger MFA (e.g., push notification).
  • High Risk → Mandatory MFA + Admin review, or block immediately.

MFA Bypass Attacks and Prevention

Attack MethodDescriptionPrevention Measures
MFA FatigueAttacker triggers repeated MFA push notifications after obtaining password, inducing user to mistakenly click "Approve"Use Number Matching (requires user to enter the number shown on screen) instead of simple push approve/deny.
SIM SwappingAttacker impersonates victim to request SIM card replacement from carrier, taking over SMS OTPAvoid using SMS as the sole MFA factor; use Authenticator App or FIDO2.
Adversary-in-the-Middle (AitM)Attacker sets up phishing site as reverse proxy, forwarding user's MFA response to real site in real-timeUse FIDO2/WebAuthn (credential bound to RP ID / Origin, anti-phishing); for OAuth Token replay protection, use DPoP or mTLS.
Session HijackingAttacker does not bypass MFA itself, but steals Session Token after MFA passesImplement strict Session Management (see Session Management Security).
Social EngineeringImpersonating IT staff via phone/message to trick user into revealing OTPSecurity awareness training, emphasize "IT staff will never proactively ask for OTP."

FIDO2 / Passkey

FIDO2 is a set of passwordless authentication standards jointly developed by the FIDO Alliance and the W3C, consisting of two components:

ComponentDescription
WebAuthnA W3C standard that defines the authentication API between browsers and websites
CTAP (Client to Authenticator Protocol)Defines the communication between the browser and external authenticators (e.g., hardware keys, mobile phones)

Passkey is the unified product name adopted by Apple, Google, and Microsoft for joint promotion; its technical essence is a FIDO2 credential. Unlike traditional FIDO2 hardware keys (such as YubiKey), Passkey additionally supports cross-device synchronization (via iCloud Keychain, Google Password Manager, etc.), allowing general users to use passwordless login without purchasing hardware.

Authenticator Types:

TypeDescriptionCommon Implementations
Platform AuthenticatorBuilt into the device, managed by the OS, uses biometrics or PIN to unlock local private keysWindows Hello (TPM), Touch ID / Face ID (macOS/iOS), Android biometrics (Android 7+)
Roaming AuthenticatorExternal devices or remote phones, portable and usable on multiple computersYubiKey (USB/NFC), mobile Cross-Device Authentication (scanning QR codes, verified via Bluetooth)

FIDO2 development work is concentrated at the WebAuthn layer, where the frontend calls browser APIs and the backend verifies challenges and response signatures; the authenticator itself is handled entirely by the OS or hardware, so developers do not need to develop for each platform individually.

SideTask
Frontend (Browser)Calls navigator.credentials.create() (registration) and navigator.credentials.get() (login)
Backend (Server)Generates random challenges, verifies response signatures, and stores user public keys
AuthenticatorHandled by the OS / hardware (developers do not need to handle this)

Modern mobile phones (iOS / Android) and desktops (Windows / macOS) have built-in platform authenticators, allowing users to use Passkeys directly with biometrics without installing additional applications.

Core Security Advantages:

  • Phishing-resistant: Credentials are bound to the website Origin; fake websites cannot trigger authentication.
  • No password leakage risk: The server only stores public keys, not passwords or shared secrets.
  • No need to remember passwords: Uses biometrics (fingerprint/face) or PIN to unlock local private keys.
  • Combines "Something You Have" + "Something You Are," naturally satisfying MFA requirements.
  • FIDO2 / Passkey handles "Authentication" (who you are), which is complementary to the "Authorization" (what you can do) of OAuth 2.0 / OIDC; the two can be used together.
.NET Implementation

The commonly used FIDO2 package in the .NET ecosystem is Fido2, which is a .NET Foundation project.

dotnet add package Fido2
dotnet add package Fido2.AspNet

Passwordless Authentication Trends

Passwordless authentication is not just FIDO2/Passkey; it includes various implementation methods:

MethodDescriptionOperating PrincipleSecurity Level
Magic LinkClick a one-time link sent to your email to complete loginMedium (depends on email security)
OTP via Authenticator AppOne-time verification code generated by TOTP / HOTP algorithmsMedium-High (does not rely on telecom carriers)
Push NotificationApp pushes an authentication request; user clicks to approve; divided into dedicated apps (e.g., Duo Security, Okta Verify) and general apps (e.g., Microsoft Authenticator, which can manage multiple accounts)Medium-High (must guard against MFA Fatigue)
FIDO2 / PasskeyPublic/private key pair + biometric unlock, phishing-resistantHighest
Certificate-basedCertificate-basedDevice/Smart Card built-in X.509 certificate, automatically verified during TLS handshakeHigh (requires PKI infrastructure management)
  • MFA Fatigue: Attackers continuously send push requests until the user gets annoyed and accidentally approves one. The mitigation is to enable "Number Matching": the login page displays a set of numbers, and the user must select the corresponding number in the app to approve, ensuring the user confirms consciously.
  • In 2022, Apple, Google, and Microsoft jointly announced support for Passkey, pushing passwordless authentication into the mainstream.
  • Enterprise adoption path: Usually progresses in stages from "Password + MFA" → "Passwordless MFA (e.g., FIDO2)" → "Fully Passwordless."

Smart Card and APDU Protocol

Smart Card is a physical card with an embedded IC chip. The chip can store keys and certificates (X.509 Certificate) and perform cryptographic operations internally; the private key never leaves the card. Common applications: Employee ID, health insurance IC cards, citizen digital certificates, and PIV (Personal Identity Verification) cards.

APDU (Application Protocol Data Unit) is the communication format between the smart card and the card reader, defined in ISO 7816-4.

C-APDU (Command APDU)

FieldLengthDescription
CLA (Class)1 byteInstruction class (e.g., 0x00 for standard ISO commands)
INS (Instruction)1 byteInstruction code (e.g., 0xA4 = SELECT, 0x20 = VERIFY PIN)
P1 / P2 (Parameters)1 byte eachInstruction parameters, meaning varies by INS
Lc (Length Command)0 or 1 byteLength of the following Data field; omitted if no data
Data0–255 bytesData sent to the card (e.g., PIN value to verify)
Le (Length Expected)0 or 1 byteExpected length of returned data; omitted if no return needed

R-APDU (Response APDU)

FieldLengthDescription
Data0–255 bytesData returned by the card (e.g., certificate content read)
SW1 (Status Word 1)1 byteHigh byte of status code
SW2 (Status Word 2)1 byteLow byte of status code

Common status codes: 0x9000 = Success (Normal Ending); 0x6982 = Security status not satisfied (e.g., PIN not verified); 0x63CX = PIN verification failed, X attempts remaining.

APDU Security Considerations

  • PIN Verification (INS = 0x20): PIN is sent in plaintext via C-APDU to the card for comparison. If the communication link between the reader and the card is not encrypted, the PIN may be intercepted. High-security scenarios (e.g., PKI smart cards) should use a Secure Channel Protocol (SCP) to establish an encrypted channel.
  • Denial of Service Protection: After consecutive PIN verification failures reach the limit (usually 3 times), the card automatically blocks. It must be unlocked via PUK (PIN Unlock Key) to prevent brute-force attacks.
  • Private Key Security: The chip design ensures that the private key is only used for internal signing or decryption operations and cannot be "exported" in its raw form by any command.

OAuth 2.0 and OIDC Comparison Table

AspectOAuth 2.0OIDC (OpenID Connect)
PositioningAuthorization FrameworkAuthentication layer built on top of OAuth 2.0
Core Problem Solved"Do you allow an application to operate a resource on your behalf?""Who are you? (Authentication) + optional authorization"
Main OutputAccess TokenID Token (Identity Claims) + Access Token
Token FormatNot enforced (can be an opaque string)ID Token must be a JWT (JSON Web Token)
User Data RetrievalRequires additional Resource Server API callsObtained via UserInfo Endpoint or by parsing the ID Token (JWT) directly
Typical Use Case"Let a third-party app read your Google Calendar""Log in to a third-party website using your Google account" (SSO, Single Sign-On)

Division of Labor between OAuth 2.0 and OIDC

  • OAuth 2.0 = Authorization (I allow App A to access Google Drive on my behalf).
  • OIDC = Authentication + Authorization (Who am I + What do I allow).
  • OIDC does not replace OAuth 2.0; it adds "who you are" capabilities on top of it.
  • Access Token vs Refresh Token: Access Token is short-lived (minutes to hours), sent with API requests; Refresh Token is long-lived (days to weeks), used only to request a new Access Token from the Authorization Server, not sent to the Resource Server, reducing leakage risk.

Relationship Diagram of OAuth, OIDC, and Token Formats

Diagram
Diagram

OAuth 2.0 Authorization Code Flow

The Authorization Code Flow is the most secure and commonly used OAuth 2.0 flow, suitable for Web applications with a backend server. When paired with PKCE (Proof Key for Code Exchange), it is also suitable for SPAs and mobile applications.

Diagram

OAuth 2.0 Grant Types Selection Guide

Grant TypeUse CaseSecurity Notes
Authorization Code + PKCEWeb App (SPA/Backend), Mobile AppRecommended. PKCE prevents Authorization Code interception.
Client CredentialsServer-to-server (Machine-to-Machine), no user involvementClient Secret must be kept secure; do not embed in frontend code.
Device CodeInput-constrained devices (e.g., Smart TV, IoT)User must complete authorization on another device.
ImplicitSPA (Legacy)Deprecated (Removed in OAuth 2.1). Token exposed in URL Fragment, prone to theft. Use Authorization Code + PKCE instead.
Resource Owner PasswordLegacy system migrationDeprecated (Removed in OAuth 2.1). User gives credentials directly to third-party app, violating OAuth design principles.
  • OAuth 2.1 draft integrates security best practices: Authorization Code flow requires PKCE by default (S256 is the preferred method, plain should not be used), with exceptions for confidential clients using OIDC nonce, etc.; removes Implicit and Resource Owner Password flows; Public client Refresh Tokens must use sender-constrained binding or one-time rotation.
  • state parameter: Prevents CSRF (Cross-Site Request Forgery) attacks; the client generates a random value and verifies consistency upon return.
  • scope minimization: Request only necessary scopes (e.g., openid profile instead of openid profile email phone address), adhering to the principle of least privilege.

API Authentication Mechanism Comparison Table

MechanismTransmission MethodSecurityUse Case
API KeyHTTP Header (e.g., X-API-Key) or Query StringLow (static string, requires manual rotation if leaked)Low-sensitivity APIs, rate limiting
Bearer Token (JWT)Authorization: Bearer <token>Medium-High (short-lived, carries claims, verifiable)API access after user authentication
OAuth 2.0 Client CredentialsAuthorization: Bearer <token> (exchanged via client_id + client_secret)High (short-lived token, supports scope limitation)Machine-to-Machine (M2M) communication
Mutual TLS (mTLS)TLS handshake level, mutual certificate verificationHighest (transport layer verification, cannot be replayed)Microservice communication, high-security finance/medical scenarios

API Key Security Notes

  • API Keys must not be embedded in frontend code or version control (git commit); they should be injected via environment variables or a Secret Manager.
  • API Keys are only suitable for "identifying the caller" (e.g., usage statistics, rate limiting) and should not be used as the sole authentication mechanism.
  • If user identity authentication is required, use OAuth 2.0 Tokens instead.
ASP.NET Core JWT Authentication Setup
csharp
// Program.cs — JWT Bearer authentication setup
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

// Read JWT parameters from configuration
IConfigurationSection jwtSettings = builder.Configuration.GetSection("Jwt");
byte[] keyBytes = Encoding.UTF8.GetBytes(jwtSettings["Key"]!);

builder.Services
    .AddAuthentication(options => {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options => {
        options.TokenValidationParameters = new TokenValidationParameters {
            ValidateIssuer = true,
            ValidIssuer = jwtSettings["Issuer"],
            ValidateAudience = true,
            ValidAudience = jwtSettings["Audience"],
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(keyBytes),
            ValidateLifetime = true,
            ClockSkew = TimeSpan.FromMinutes(1)
        };
    });

builder.Services.AddAuthorization();

WebApplication app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

// Protected endpoint
app.MapGet("/api/protected", () => "Hello, authenticated user!")
    .RequireAuthorization();

app.Run();
jsonc
// appsettings.json — JWT configuration section
{
  "Jwt": {
    "Key": "YourSuperSecretKeyAtLeast32CharsLong!!", // Use Secret Manager in production
    "Issuer": "https://your-app.example.com",
    "Audience": "https://your-app.example.com"
  }
}
ASP.NET Core Claims-based Authorization Policy
csharp
// Program.cs — Register authorization policies
builder.Services.AddAuthorization(options => {
    // Role-based policy
    options.AddPolicy("AdminOnly", policy =>
        policy.RequireRole("Admin"));

    // Claim-based policy: requires specific department
    options.AddPolicy("FinanceDepartment", policy =>
        policy.RequireClaim("department", "finance"));

    // Composite policy: Admin role + Taiwan region
    options.AddPolicy("TaiwanAdmin", policy =>
        policy
            .RequireRole("Admin")
            .RequireClaim("region", "TW"));

    // Custom policy: age verification
    options.AddPolicy("Over18", policy =>
        policy.RequireAssertion(context => {
            Claim? birthDateClaim = context.User.FindFirst("birth_date");

            if (birthDateClaim is null
                || !DateTime.TryParse(birthDateClaim.Value, out DateTime birthDate)) {
                return false;
            }

            int age = DateTime.Today.Year - birthDate.Year;

            if (birthDate.Date > DateTime.Today.AddYears(-age)) {
                age--;
            }

            return age >= 18;
        }));
});

// Apply to endpoints
app.MapGet("/api/admin/dashboard", () => "Admin Dashboard")
    .RequireAuthorization("AdminOnly");

app.MapGet("/api/finance/reports", () => "Finance Reports")
    .RequireAuthorization("FinanceDepartment");

app.MapGet("/api/restricted", () => "Restricted Content")
    .RequireAuthorization("Over18");
Password Hashing (BCrypt)
csharp
// Install NuGet package: BCrypt.Net-Next
// dotnet add package BCrypt.Net-Next

using BCrypt.Net;

public static class PasswordHasher {
    // Recommended Work Factor: 12 or higher (computation time doubles with each increment)
    private const int WorkFactor = 12;

    /// <summary>
    /// Hashes a plain text password using BCrypt.
    /// </summary>
    public static string Hash(string plainPassword) {
        return BCrypt.Net.BCrypt.HashPassword(plainPassword, WorkFactor);
    }

    /// <summary>
    /// Verifies a plain text password against a stored BCrypt hash.
    /// </summary>
    public static bool Verify(string plainPassword, string hashedPassword) {
        return BCrypt.Net.BCrypt.Verify(plainPassword, hashedPassword);
    }
}

// Usage example
// string hash = PasswordHasher.Hash("MyP@ssw0rd");
// bool isValid = PasswordHasher.Verify("MyP@ssw0rd", hash); // true
  • BCrypt: Built-in salt, adjustable computational cost (Work Factor), currently the most widely used password hashing algorithm.
  • Argon2 (Argon2id): Winner of the 2015 Password Hashing Competition, resistant to GPU/ASIC attacks (adjustable memory cost), security superior to BCrypt, but has a smaller package ecosystem.
  • Forbidden: General hashing functions like MD5, SHA-1, and SHA-256 are unsuitable for password storage (no salt, too fast to compute, vulnerable to brute-force and rainbow table attacks).
  • ASP.NET Core Identity defaults to PBKDF2 (with HMAC-SHA256/SHA512), using a 128-bit salt and 10,000+ iterations.

JWT (JSON Web Token)

JWT is an open standard (RFC 7519) based on JSON, used for securely passing claims between parties. It consists of three Base64Url-encoded segments separated by .: Header.Payload.Signature.

  • Header: Declares the token type (typ: "JWT") and the signature algorithm (alg, e.g., HS256, RS256).
  • Payload: Contains Claims (user information and token metadata), Base64Url-encoded but not encrypted; anyone can decode and read it.
  • Signature: A hash signature of the first two segments, verifying the token's integrity and source credibility.

Common Claims

ClaimNameDescription
issIssuerThe issuer of the token (e.g., https://auth.example.com)
subSubjectThe subject of the token, usually the user ID
audAudienceThe intended recipient of the token (Resource Server)
expExpiration TimeExpiration time (Unix Timestamp)
iatIssued AtIssuance time
nbfNot BeforeToken is invalid before this time
jtiJWT IDUnique token identifier, can be used to prevent replay attacks

JWS and JWE

AspectJWS (JSON Web Signature)JWE (JSON Web Encryption)
Structure SegmentsThree segments (Header.Payload.Signature)Five segments (Header.EncryptedKey.IV.Ciphertext.AuthTag)
Payload ReadabilityBase64Url encoded, can be decoded and read directlyEncrypted, cannot be read by third parties
Protection GoalIntegrity + Source verification (anti-tampering)Confidentiality (anti-reading)
Practical Usage FrequencyDefault format for daily JWTsUsed only when Payload contains sensitive personal data (e.g., ID number, medical records)

Signature Algorithms

AlgorithmTypeKeyUse Case
HS256Symmetric (HMAC-SHA256)Same shared key for signing and verificationInternal to a single service, no need for cross-service verification
RS256Asymmetric (RSA-SHA256)Private key for signing, public key for verificationAuthorization Server signs, Resource Server verifies with public key; public key can be published via JWKS Endpoint
ES256Asymmetric (ECDSA-SHA256)Private key for signing, public key for verificationSame as RS256, but keys are shorter and performance is better; suitable for mobile devices and high-traffic scenarios

Common JWT Security Attacks

  • alg: none bypass: Attacker changes the Header's alg to "none", removes the Signature, and forges the token. Countermeasure: The server must explicitly limit allowed algorithms via a whitelist and reject none.
  • RS256 → HS256 confusion attack: If the server mistakenly allows the verification algorithm to be dynamically determined by the token header, an attacker can change alg to HS256 and forge the signature using the RS256 public key (which is publicly available) as the HMAC key. Countermeasure: Hardcode the expected algorithm on the server side; do not trust the alg claim in the header.
  • Replay Attack: Intercepting a valid token and sending it repeatedly. Countermeasure: Set a reasonable exp (short-lived); for high-sensitivity operations, use jti and a blacklist of used tokens.

Identity Federation and SCIM

Identity Federation: Allows users to access resources of another organization using their identity credentials from one organization, without creating separate accounts in each organization.

AspectSAML 2.0OIDC
Transmission MethodHTTP POST Binding: XML Assertion passed via browser through auto-submitted HTML FormToken exchanged directly by backend with Authorization Server, not passed through browser
FormatXML (bulky)JWT (compact, can carry Authorization: Bearer header)
Mobile / SPA Support❌ Relies on browser page redirects; native apps and SPAs cannot use directly✅ Authorization Code + PKCE suitable for all client types
Microservice Auth❌ XML Assertion is bulky, unsuitable for high-frequency API calls✅ JWT can be verified locally at the Gateway or by individual services, no centralized verification needed
Use CaseEnterprise SSO (legacy Web apps, ADFS integration)Consumer apps, mobile apps, SPAs, modern API architectures

SAML 2.0 Core Roles and Assertion

  • SAML 2.0 core roles: IdP (Identity Provider), SP (Service Provider).
  • SAML Assertion contains Authentication Statement, Attribute Statement, and Authorization Decision Statement.

SCIM (System for Cross-domain Identity Management): A standardized REST API for automating account lifecycle management (create, read, update, disable) across systems. When an employee joins, the HR system automatically creates accounts in Azure AD, Slack, Jira, etc., via SCIM; when they leave, it automatically disables them.

SCIM manages "whether an account exists," while SAML/OIDC manages "how to log in." They are complementary and together form the foundation of modern cross-organizational identity management.

Directory Services

Directory services are infrastructure for centrally managing identity information such as user accounts, groups, and devices:

Service/ProtocolDescription
LDAP (Lightweight Directory Access Protocol)Lightweight protocol for querying and modifying directories. Data is organized in a tree structure (DIT, Directory Information Tree), with each node uniquely identified by a DN (Distinguished Name), e.g., cn=John,ou=Users,dc=example,dc=com.
Active Directory (AD)Microsoft's directory service implementation, using LDAP as the access protocol and Kerberos as the authentication protocol. Features include account management, Group Policy (GPO), and DNS integration.
Azure AD (Entra ID)Microsoft's cloud identity service, supporting OAuth 2.0 / OIDC / SAML. It is a cloud-native identity management platform, but it does not use LDAP or Kerberos at the underlying layer.
OpenLDAPOpen-source LDAP server, a common directory service implementation in Linux environments.

LDAP Basic Concepts

  • DN (Distinguished Name): The full path to a node, e.g., cn=John,ou=Users,dc=example,dc=com.
  • RDN (Relative Distinguished Name): The unique name of a node at the same level, e.g., cn=John.
  • Common attribute prefixes: cn (Common Name), ou (Organizational Unit), dc (Domain Component), uid (User ID).
  • LDAPS (LDAP over TLS/SSL): Uses Port 636, encrypts LDAP communication, prevents plaintext transmission of account passwords.
OpenLDAP Basic Query Commands
bash
# Search all users (anonymous bind, only for directories allowing anonymous queries)
ldapsearch -x -H ldap://ldap.example.com \
  -b "dc=example,dc=com" "(objectClass=inetOrgPerson)"

# Bind and query with administrator account (-D is bind DN, -W is interactive password input)
ldapsearch -x -H ldap://ldap.example.com \
  -D "cn=admin,dc=example,dc=com" -W \
  -b "ou=Users,dc=example,dc=com" \
  "(uid=john)" cn mail memberOf

# Encrypted query via LDAPS
ldapsearch -x -H ldaps://ldap.example.com \
  -D "cn=admin,dc=example,dc=com" -W \
  -b "dc=example,dc=com" "(cn=John*)"

# View directory structure (list DNs only, no attributes)
ldapsearch -x -H ldap://ldap.example.com \
  -b "dc=example,dc=com" -s sub "(objectClass=*)" dn
  • -x: Use simple bind instead of SASL.
  • -b: Base DN to start the search.
  • -s: Search scope (base = self only, one = direct children, sub = entire subtree).
  • Official documentation: https://openldap.org/doc/admin26/guide.html

Kerberos Authentication

Kerberos is a network authentication protocol based on symmetric keys (developed by MIT) and is the default authentication mechanism for Active Directory. Its core concept is the "Ticket": users only need to authenticate their identity with the KDC once to obtain a ticket to access multiple services (SSO).

Core Components:

ComponentFull NameResponsibility
KDCKey Distribution CenterThe core Kerberos server responsible for issuing tickets. In AD, it is served by the Domain Controller.
ASAuthentication ServiceA sub-component of the KDC that verifies user identity and issues the TGT.
TGSTicket Granting ServiceA sub-component of the KDC that issues Service Tickets for specific services based on the TGT.
TGTTicket Granting TicketA "pass" obtained after the user is verified by the AS, used to request Service Tickets from the TGS without re-entering a password.
Service TicketCredentials for accessing specific services (e.g., file servers, databases).
Diagram

Kerberos Security Considerations

  • Time Synchronization: Kerberos relies on timestamps to prevent replay attacks. The time difference between the Client and the KDC must not exceed 5 minutes by default.
  • For details on attack techniques targeting Kerberos (Golden Ticket, Silver Ticket, Pass-the-Ticket, Kerberoasting), see Credential Theft and Lateral Movement Techniques.

RADIUS and TACACS+

When an enterprise manages hundreds of network devices, maintaining accounts individually on each device is extremely costly. RADIUS and TACACS+ solve this problem: a centralized AAA server handles authentication, authorization, and accounting, while network devices act as "forwarders," sending user credentials to the server for verification.

Typical Architecture: User → Network Device (acting as AAA Client, e.g., switch, AP, VPN Gateway) → AAA Server (RADIUS / TACACS+)

Comparison AspectRADIUSTACACS+
Full NameRemote Authentication Dial-In User ServiceTerminal Access Controller Access-Control System Plus
DeveloperIETF Open Standard (RFC 2865/2866)Cisco-led (Proprietary protocol, later published)
Transport ProtocolUDP (Port 1812/1813)TCP (Port 49)
Encryption ScopeEncrypts only the password fieldEncrypts the entire packet (higher security)
AAA IntegrationAuthentication and authorization merged in one packetAuthentication, authorization, and accounting are completely separated (finer granularity)
Use CaseNetwork access authentication (e.g., Wi-Fi 802.1X, VPN)Network device management access (e.g., CLI command authorization for routers/switches)

RADIUS and TACACS+ Use Cases

  • The "Dial-In" in RADIUS originated from the dial-up modem era but is now widely used for various network access authentications, not limited to dial-up.
  • RADIUS is suitable for "high-volume user network access authentication" (e.g., Wi-Fi, VPN).
  • TACACS+ is suitable for "network administrator device management," allowing for granularity down to "which CLI commands are allowed."
  • Both can coexist: RADIUS manages Wi-Fi user authentication, while TACACS+ manages network device administrator authentication.

Privileged Access Management (PAM)

PAM (Privileged Access Management) specifically controls access to high-privilege accounts (e.g., Domain Admin, root, DBA) and is a key component of Zero Trust Architecture.

Core PAM Functions:

FunctionDescription
Password VaultCentralized storage and management of privileged account passwords; users do not know the passwords directly and connect via the PAM system proxy.
Session RecordingRecords the entire process of privileged operations (keyboard input, screen) for post-incident auditing.
Just-in-Time Access (JIT)Grants privileges only when needed and automatically revokes them after use, preventing long-term high-privilege account holding.
Automatic Password RotationAutomatically changes privileged account passwords after each use or on a schedule to reduce leakage risk.
Least Privilege ProxyAllows users to perform specific privileged operations (e.g., restarting a service) without granting full administrator rights.

Just-in-Time (JIT) Access

JIT access is an advanced implementation of the principle of least privilege:

  • Request-based: Users submit access requests when needed, which are granted after approval.
  • Time-limited: Access is granted with an expiration time (e.g., 4 hours) and automatically revoked upon expiry.
  • Audit Trail: Every JIT request leaves a complete record (who, when, why, what was done).
  • Cloud Implementation: Azure AD PIM (Privileged Identity Management), AWS IAM Identity Center temporary privilege escalation.

Identity Governance and Administration (IGA) and Identity Lifecycle

IAM (Identity and Access Management) is the overall framework for managing "digital identities" and "access rights," covering four aspects:

AspectDescriptionCorresponding Section
AuthenticationVerifies user identityAuthentication Factors, FIDO2/Passkey, Kerberos
AuthorizationDetermines what resources an authenticated identity can accessAccess Control Models (RBAC / ABAC), OAuth 2.0
Identity LifecycleManages the entire process from account creation to deactivationIGA and Identity Lifecycle (this chapter)
Access GovernanceAuditing, review, and separation of duties to ensure compliancePAM, IGA

IGA (Identity Governance and Administration) is the higher-level governance framework for IAM, covering the complete lifecycle management of identities:

Lifecycle StageDescriptionTypical Operation
JoinerAccount creation, role assignment, device provisioningHR system triggers SCIM to automatically create accounts in AD, Email, Slack, etc.
MoverEmployee transfer or job changeRevoke old roles, grant new roles (prevents Permission Creep).
LeaverAccount deactivation, access revocation, data handoverAutomatically disable all system accounts, revoke VPN/Badge access, retain audit logs.

Key IGA Mechanisms:

  • Access Review / Recertification: Periodic (e.g., quarterly) review by managers of subordinates' access rights to confirm business necessity.
  • Separation of Duties (SoD): Ensures conflicting permissions are not granted to the same person (e.g., "Create Vendor" and "Approve Payment" cannot be performed by the same individual).
  • Role Mining: Analyzes existing permission patterns to derive standard role definitions, reducing the risk of role explosion.

Service Account Management

Service accounts are used for applications, scheduled tasks, or inter-system communication and are not bound to specific individuals:

Service Account Security Best Practices

PracticeDescription
One Service, One AccountEach application or service uses a dedicated service account to avoid sharing.
Prohibit Interactive LoginService accounts should not allow interactive logins like RDP or SSH (Windows: disable "Allow log on locally" right).
Password ManagementUse Managed Service Accounts (MSA/gMSA, Windows AD) for automatic password management; use PAM for automatic rotation in non-AD environments.
Least PrivilegeGrant only the minimum permissions required for the service to function; avoid using Admin or root identities.
Secret InjectionPasswords/keys are injected via environment variables, Secret Manager, or Key Vault; do not write them in configuration files or code.
Monitoring and AuditingMonitor service accounts for anomalous behavior (e.g., logins from unexpected sources, access to unexpected resources).

Decentralized Identity

Self-Sovereign Identity (SSI) is an identity management paradigm where users have full control over their identity data without relying on a central identity provider:

ConceptDescription
DID (Decentralized Identifier)W3C standard, a decentralized unique identifier that does not rely on a central registry. Format: did:web:example.com:user:123.
Verifiable Credential (VC)Digital credentials issued by an issuer (e.g., diploma, employee ID); holders can selectively disclose information.
Verifiable Presentation (VP)The holder selects a combination of information from multiple VCs to present to a verifier.
Digital WalletA user-side application that stores and manages DIDs and VCs.

SSI Value and Status

  • Core value of SSI: Principle of Least Disclosure. For example, when verifying "over 18," one only needs to present a "Yes/No" proof without revealing the full birthdate.
  • Currently in the early adoption stage; the EU eIDAS 2.0 regulation promoting the EU Digital Identity Wallet is a large-scale implementation.
  • Difference from Traditional Identity Federation: In federation, the IdP knows which SPs the user logged into (privacy concern); in SSI, the user presents the VC directly, and the issuer does not know when or where it is used.

Linux / Windows Identity Management Comparison Table

Management AspectLinuxWindows
Account Creationuseradd -m john / passwd johnnet user john P@ssw0rd /add, or via ADUC (Active Directory Users and Computers) GUI
Account Info Storage/etc/passwd (account info), /etc/shadow (password hash)SAM (Security Accounts Manager, local accounts), AD database (ntds.dit, domain accounts)
Group Managementgroupadd, usermod -aG group usernet localgroup, AD security groups
File Permissionschmod (rwx), chown (owner), POSIX ACL (setfacl)NTFS ACL, icacls command-line tool
Authentication ModulePAM (Pluggable Authentication Modules)LSASS (Local Security Authority Subsystem Service)
Directory Services/SSOSSSD + OpenLDAP / FreeIPA + KerberosActive Directory + Kerberos
Remote AuthenticationSSH Key-based, KerberosKerberos (AD), NTLM (Legacy)
Linux PAM Configuration Example
bash
# /etc/pam.d/common-auth — Authentication module stack (Ubuntu/Debian)
# Format per line: module-type  control-flag  module-path  [arguments]

# Standard Unix password authentication
auth    required    pam_unix.so     nullok

# Account lockout: Lock for 300 seconds after 5 consecutive failures
auth    required    pam_faillock.so preauth deny=5 unlock_time=300
auth    required    pam_faillock.so authfail deny=5 unlock_time=300

# Password complexity requirements (requires libpam-pwquality)
# /etc/security/pwquality.conf sets minimum length, case, digit, and special character requirements
password    requisite   pam_pwquality.so retry=3 minlen=12 dcredit=-1 ucredit=-1 lcredit=-1 ocredit=-1
password    required    pam_unix.so sha512 shadow use_authtok
  • required: If the module fails, the final result is failure, but subsequent modules are still executed (to prevent information leakage via response time).
  • requisite: If the module fails, it returns failure immediately without executing further.
  • Linux PAM and PAM (Privileged Access Management) are completely different concepts; the name is a coincidence.
SSH Key-based Authentication Setup
bash
# === Client side (generate key pair) ===

# Generate Ed25519 key pair (recommended algorithm, shorter and more secure than RSA)
ssh-keygen -t ed25519 -C "[email protected]"
# Default storage path: ~/.ssh/id_ed25519 (private key), ~/.ssh/id_ed25519.pub (public key)

# Copy public key to remote server
ssh-copy-id -i ~/.ssh/id_ed25519.pub [email protected]

# === Server side (/etc/ssh/sshd_config security hardening) ===

# Enable public key authentication
PubkeyAuthentication yes

# Disable password authentication (only allow key login)
PasswordAuthentication no

# Disable root direct login
PermitRootLogin no

# Restrict allowed users
AllowUsers john admin

# Restart SSH service after changing settings
# sudo systemctl restart sshd
  • Private keys must have appropriate permissions: chmod 600 ~/.ssh/id_ed25519.
  • It is recommended to set a Passphrase for the private key and use ssh-agent to avoid entering it every time.
  • Ed25519 vs RSA: Ed25519 key length is shorter (256-bit vs RSA recommended 3072+ bit), signing is faster, and it is resistant to side-channel attacks.

Zero Trust Architecture Comparison Table

Traditional Perimeter Security vs. Zero Trust

AspectTraditional Perimeter Security (Moat Model)Zero Trust Architecture
Core AssumptionInternal network is trusted, external is untrustedNo network, device, or user is trusted by default
Verification TimingTrusted after passing perimeter verification (e.g., VPN); no further verificationRe-verify identity and authorization for every resource access
Network PerimeterClear firewall perimeterNo perimeter concept; Identity is the perimeter
Lateral Movement RiskHigh (attacker can freely access internal resources once inside)Low (micro-segmentation and continuous verification block lateral movement)
Use CaseFixed office, employees work on internal networkCloud, remote work, hybrid work environments

Three Core Principles of Zero Trust

PrincipleDescription
Never Trust, Always VerifyDo not automatically trust just because of being on the internal network; verify identity, device status, and authorization for every access.
Least PrivilegeGrant only the minimum permissions required to complete the task; revoke immediately after access expires or the task is finished.
Assume BreachAssume the attacker is already inside; design with isolation, monitoring, and rapid detection in mind rather than relying solely on perimeter defense.

Key Zero Trust Technical Components

Technical ComponentPurpose Description
IAM + MFAFoundation of identity verification; confirms "who you are" and requires multi-factor authentication.
PAM (Privileged Access Management)Controls high-privilege accounts (e.g., Admin, root), limiting the time and scope of privileged operations.
Micro-segmentationSegments the network into small zones to limit the scope of lateral movement for attackers.
EDR (Endpoint Detection and Response)Continuously monitors endpoint behavior to detect anomalies and respond automatically.
SIEM / SOARCentralizes log collection (SIEM, Security Information and Event Management) and automates security incident response (SOAR, Security Orchestration, Automation and Response).

NIST SP 800-207 Zero Trust Architecture Core Components

ComponentFull NameResponsibility
PEPolicy EngineMakes access allow/deny decisions based on enterprise policy, user identity, device status, threat intelligence, etc.
PAPolicy AdministratorReceives PE decisions and establishes or terminates communication paths (e.g., issuing short-term certificates, setting up VPN tunnels).
PDPPolicy Decision PointCollective term for PE + PA; represents the decision side; PDP is responsible for "deciding," PEP for "enforcing."
PEPPolicy Enforcement PointIntercepts all access requests, queries the PA for a decision, and then allows or blocks. Deployed as a gateway in front of resources.
Diagram

Software Defined Perimeter (SDP)

SDP is an implementation of Zero Trust Architecture with the core philosophy of "Authenticate before Connect."

Core Components:

ComponentDescription
SDP ControllerVerifies user and device identity and determines the list of accessible services.
Initiating Host (IH)The client initiating the connection; must complete identity verification with the Controller first.
Accepting Host (AH)The host providing the service; denies all connections by default, accepting only IHs authorized by the Controller.

SDP vs. Traditional VPN:

Comparison AspectSDPTraditional VPN
Connection LogicAuthenticate identity first, then establish connection (service is invisible externally)Establish encrypted tunnel first, then authenticate identity
Access GranularityIndividual application levelNetwork level (access to the entire subnet once inside VPN)
Attack SurfaceExtremely small (service listens on no public ports, known as "Black Cloud")Larger (VPN gateway must expose ports)
  • SDP is also known as "Black Cloud": Unauthenticated users cannot see any services, and even Port Scans cannot detect them.
  • Under Zero Trust Architecture, SDP can replace or supplement VPNs to provide finer-grained access control.

Zero Trust Architecture and FIDO2 Integration

The "Never Trust, Always Verify" principle of Zero Trust aligns perfectly with FIDO2 passwordless authentication:

Integration AspectImplementation MethodSecurity Benefit
Strengthened Identity VerificationReplace traditional passwords with FIDO2/WebAuthn; use biometrics + hardware keys for every resource accessPhishing-resistant, no password leakage risk, native MFA
Dynamic Trust ScoringCombine FIDO2 authentication results with device trust status and location info to dynamically adjust access rightsFine-grained authorization decisions, reduced false positives
Passwordless PAMPrivileged accounts use FIDO2 authentication, no longer relying on shared passwords or SSH keysEliminates complexity of privileged account password management
Decentralized AuthenticationFIDO2 private keys stored on user devices, no central password server neededReduces single point of failure, improves resilience

Technical Architecture Integration:

User Device (FIDO2 Authenticator) → PEP (Policy Enforcement Point) → PA (Policy Administrator) → PE (Policy Engine + FIDO2 Verification Result)

For every resource access request, the PEP requires FIDO2 authentication; upon success, the result is passed to the PE as an input for the trust decision.

Cloud and Mobile Device Security

Cloud Service Model Comparison Table

Service ModelFull NameProvider Management ScopeCustomer Management ScopeTypical Services
IaaSInfrastructure as a ServicePhysical machines, network, storage, virtualizationOS, middleware, runtime, applications, dataAWS EC2, Azure VM, GCP Compute Engine
PaaSPlatform as a ServiceIaaS scope + OS, middleware, runtimeApplications, dataHeroku, Azure App Service, AWS Elastic Beanstalk
FaaSFunction as a ServicePaaS scope + runtime management, auto-scalingFunction code, trigger configurationAWS Lambda, Azure Functions, GCP Cloud Functions
SaaSSoftware as a ServicePaaS scope + applicationsData (user operation level)Gmail, Microsoft 365, Salesforce

NIST Five Essential Characteristics of Cloud Computing

The five essential characteristics of cloud computing defined by NIST (National Institute of Standards and Technology) SP 800-145:

  1. On-demand Self-service: Users can provision computing resources themselves without human intervention.
  2. Broad Network Access: Accessible via standard network mechanisms from various devices.
  3. Resource Pooling: Provider pools resources and dynamically assigns them to multiple users (multi-tenant model).
  4. Rapid Elasticity: Resources can be scaled up or down rapidly, appearing as infinite to the user.
  5. Measured Service: Automatically monitors and controls resource usage, billing based on consumption (Pay-as-you-go).

Industry Scenarios

  • IaaS Industry Scenario: Enterprise moves on-premises VMs to the cloud as-is (Lift and Shift), managing OS and applications themselves.
  • PaaS Industry Scenario: Development team deploys .NET applications to Azure App Service, without managing underlying OS and Runtime updates.
  • SaaS Industry Scenario: Entire company uses Microsoft 365 for email and document collaboration; IT only manages accounts and authorization.

Shared Responsibility of Cloud Service Models (IaaS / PaaS / SaaS / FaaS)

Security LayerIaaSPaaSFaaSSaaS
Physical SecurityProviderProviderProviderProvider
Network InfrastructureProviderProviderProviderProvider
OS PatchingCustomerProviderProviderProvider
Runtime ConfigurationCustomerCustomerProviderProvider
Application SecurityCustomerCustomerCustomerProvider
Data SecurityCustomerCustomerCustomerCustomer
Identity & Access ManagementCustomerCustomerCustomerCustomer

Rule: From IaaS → SaaS, the customer's management scope shrinks, but data security and identity management are always the customer's responsibility.

Diagram

Shared Responsibility Model Transition Diagram

Diagram

Cloud Security Posture Management and Workload Protection

The most common source of security incidents in cloud environments is Misconfiguration, not vulnerability exploitation. Runtime protection for workloads (VMs, containers, Serverless) also requires cloud-native tools; traditional EDR cannot be applied directly. The following solutions address different layers of protection:

SolutionFull NameFocused ProblemTypical Function
CSPMCloud Security Posture ManagementAre configurations correct?Continuously scans for misconfigurations (e.g., public S3 buckets, unencrypted databases) to ensure compliance with security benchmarks (CIS Benchmark).
CWPPCloud Workload Protection PlatformIs the workload under attack?Protects runtime security of VMs, containers, and Serverless; provides threat detection, vulnerability scanning, and file integrity monitoring.
CIEMCloud Infrastructure Entitlement ManagementAre permissions excessive?Analyzes actual usage of IAM roles and permissions to detect excessive permissions and high-risk privileged accounts.
CNAPPCloud-Native Application Protection PlatformOverall cloud application securityIntegrates CSPM + CWPP + CIEM to provide comprehensive protection from development to runtime (Gartner-defined category).

Cloud Security Platform Division of Labor

  • CSPM manages the "configuration layer," CWPP manages "runtime," and CIEM manages the "permissions layer"; they are independent but complementary.
  • CNAPP is an integrated platform for all three, providing a unified interface for the three dimensions of cloud security.
Diagram

Serverless / FaaS Security

Security AspectDescription
Function PermissionsEach function should have a dedicated IAM role, granting only the minimum required permissions (do not share a high-privilege role).
DependenciesServerless functions also have supply chain risks; SCA scanning is required.
Cold Start AttacksIf unverified configurations or Secrets are loaded during function re-initialization, they may be exploited by attackers.
Event InjectionAttackers inject malicious payloads via trigger events (e.g., malicious S3 object names, forged API Gateway requests).
Execution Time LimitsSet reasonable timeouts and memory limits to prevent abuse as cryptocurrency mining nodes.
Logging and MonitoringServerless has no persistent storage; logs must be exported to a centralized logging platform.

Specifics of Serverless Security

  • The provider manages the OS and Runtime; customers cannot install traditional host-based security tools (EDR, antivirus).
  • The security focus shifts from "infrastructure protection" to "application code and configuration security."
  • While the attack surface is reduced (no OS to attack), function logic vulnerabilities (e.g., IDOR, injection) still exist.

Warm Start Container Reuse Data Residue Risk

To improve performance, cloud platforms (AWS Lambda, Azure Functions, etc.) do not immediately destroy containers after function execution but keep them (Warm) for the next call, known as Warm Start (as opposed to Cold Start, which re-initializes the container).

Security Concern: Database connections, temporary objects, and cached credentials declared outside the Handler function (i.e., in the global variable scope) have the same lifecycle as the container. If not cleaned up properly, events triggered by subsequent different users may read sensitive information left over from the previous execution (e.g., other users' Session data, API Tokens).

Security Practices:

  • Declare sensitive data only inside the Handler function (re-initialized on every call).
  • Globally shared connection objects (e.g., DB Connection Pool) should not contain user-specific authentication information.
  • Actively clear internal function caches or tokens after each request ends.

Multi-tenancy Security Risks

The nature of cloud "resource pooling" means multiple tenants share underlying hardware, leading to three major risks:

  • Side-channel Attack: When sharing CPU cache or memory buses, malicious tenants can infer other tenants' sensitive data through timing analysis (e.g., VM Escape to Hypervisor, L1TF/Foreshadow attacks on shared L1 cache).
  • Cross-tenant Data Leakage: When storage is not fully isolated, data from a previous tenant may remain after disk segments are reallocated (Data Remanence); or API permission misconfigurations may lead to accessing other tenants' resources.
  • Noisy Neighbor: Other tenants on the same physical host consume large amounts of CPU, I/O, or network bandwidth, causing your service performance to degrade. While not a malicious attack, it affects availability.

Cloud Access Security Broker (CASB)

CASB is a security gateway deployed between users and cloud services, providing four pillars of functionality:

PillarDescription
VisibilityDiscovers all cloud service usage within the organization, including unauthorized Shadow IT.
ComplianceEnsures cloud usage complies with regulations (GDPR, HIPAA, etc.) and internal policies.
Threat ProtectionDetects anomalous behavior, malware uploads, and account takeovers.
Data SecurityDLP (Data Loss Prevention), encryption, and access control to prevent sensitive data leakage.

Deployment Modes:

ModeDescription
Forward ProxyIntercepts traffic from users to the cloud; requires agent installation or PAC configuration.
Reverse ProxyIntercepts traffic from the cloud to users; requires no client-side configuration.
APIScans directly via cloud service APIs; does not pass through user traffic paths.

Positioning in Defense Architecture:

  • CASB acts as a policy enforcement point between users and cloud services, integrating DLP, access control, threat protection, and compliance auditing.
  • CASB can detect Shadow IT (employees using unauthorized cloud services) and collaborate with DLP to prevent cloud data leakage.

Mobile Device Security and BYOD (Bring Your Own Device)

Mobile Application Sandbox and Permission Model

Android: UID/GID Sandbox and Permission Model

AspectDescription
Sandbox FoundationEach app is assigned a unique Linux UID (User ID) upon installation, running in an isolated process and file system namespace; other apps cannot access its private data
UID SharingApps signed by the same developer with the same certificate can declare sharedUserId to share the same UID and data directory
Permission ClassificationNormal permissions: Granted automatically at installation (no prompt); Dangerous permissions: Requested from the user at runtime (e.g., location, camera); Signature permissions: Only accessible by apps with the same signature
Mandatory Access Control (SELinux)Android 4.4+ uses SELinux in Enforcing mode to strengthen the sandbox; even with a UID, one cannot bypass SELinux policies

iOS: Transparency, Consent, and Control (TCC) Architecture

TCC (Transparency, Consent, and Control) is the framework iOS uses to manage application access to sensitive resources.

AspectDescription
Core PrincipleApplications cannot access any sensitive resources (camera, microphone, location, contacts, etc.) by default and must explicitly request authorization from the user
Authorization GranularityEach sensitive resource category is authorized independently and can be revoked at any time in "Settings → Privacy"
Sandbox MechanismEach app runs in an isolated sandbox directory and cannot directly access other apps' data or system paths
Application SigningAll apps on the App Store must undergo Apple's code signing and review; unsigned apps cannot execute (unless via TestFlight or enterprise certificates)
EntitlementsApplications declare required system capabilities (e.g., Push Notification, iCloud) at compile time; API calls exceeding Entitlements are intercepted at the sandbox layer

Android Sandbox vs. iOS TCC Comparison

AspectAndroid UID SandboxiOS TCC
Sandbox FoundationLinux UID process isolationApp sandbox directory + Entitlements
Resource Access ControlRuntime Permission: Dangerous permissions requested at runtimeTCC framework: User prompted for each resource category
Code Source VerificationGoogle Play Protect + Developer signature (sideloading possible)Apple mandatory code signing + App Store review
MAC StrengtheningSELinux Enforcing policyApple SIP (System Integrity Protection)
Control AspectDescription
Enterprise/Personal Data IsolationCorporate data and personal data are stored and managed separately on the same device
Remote WipeRemotely delete corporate data when a device is lost or an employee leaves
MDM (Mobile Device Management)Centralized management of device policies, security updates, and application whitelists
Device EncryptionEncrypt data at rest and in transit according to industry standards
Connection SecurityAvoid using public Wi-Fi for sensitive data transmission; disable unused connection features (Bluetooth, NFC, GPS)

BYOD Data Control Key Points

  • BYOD Core Challenge: The device is employee-owned, limiting enterprise control, yet it contains corporate data.
  • Upon employee departure, immediately revoke access to corporate resources and perform a remote wipe of corporate data.
  • If a device is lost or stolen, the first step is Remote Wipe of corporate data to prevent data leakage.

Development and Operations Security

SSDLC and DevSecOps Comparison Table

SSDLC (Secure Software Development Life Cycle) embeds security activities into every development phase.

Development PhaseSecurity ActivityOutput
RequirementsSecurity requirements analysis, Threat Modeling, Privacy Impact AssessmentSecurity requirements specification, data classification
DesignSecurity architecture design, Attack Surface AnalysisSecurity design document
ImplementationSecure Coding Guidelines, code reviewReviewed code
TestingSAST, DAST, penetration testing, FuzzingVulnerability report, remediation records
DeploymentSecurity Baseline, environment HardeningDeployment checklist
OperationsContinuous monitoring, Patch Management, incident responseMonitoring dashboard, remediation records

Threat Modeling

Threat modeling systematically identifies potential threats and attack paths during the design phase. Common methodologies:

MethodologyFull NameCore ConceptApplicable Phase
STRIDESpoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of PrivilegeExamine system components against six threat categories; core of Microsoft SDLDesign phase
DREADDamage, Reproducibility, Exploitability, Affected Users, DiscoverabilityQuantitatively score identified threats (1-10 scale) to prioritize remediationRisk assessment
PASTAProcess for Attack Simulation and Threat AnalysisSeven-stage process from business objectives to attack simulation; emphasizes attacker-driven risk analysisFull lifecycle

Threat Modeling Workflow

Diagram

Division of Labor: STRIDE, DREAD, and PASTA

  • STRIDE answers "What threats might the system face?"; DREAD answers "Which threat should be prioritized?". They are often used together.
  • PASTA is suitable for large organizations needing alignment with business risks; it is process-heavy but offers the broadest coverage.
  • The Microsoft Threat Modeling Tool is a free tool that can generate DFDs (Data Flow Diagrams) and automatically apply STRIDE analysis.

STRIDE Six Threat Categories Comparison

Threat CategoryDescriptionCorresponding CIA+ Attribute
SpoofingImpersonating another user or systemAuthentication
TamperingUnauthorized modification of data or codeIntegrity
RepudiationDenying that an operation was performedNon-repudiation
Information DisclosureExposing information to unauthorized partiesConfidentiality
Denial of ServiceMaking the system unable to provide normal servicesAvailability
Elevation of PrivilegeGaining permissions beyond authorized scopeAuthorization

Secure Code Review Checklist

Check CategoryKey Items
Input ValidationAre all external inputs (users, APIs, files) validated against a whitelist and sanitized?
Output EncodingIs output correctly encoded before being sent to HTML/SQL/OS commands to prevent injection attacks?
Authentication & AuthorizationAvoid hardcoded passwords; use strong password hashing (bcrypt/Argon2); perform authorization checks server-side
Session ManagementDo Session Tokens have sufficient entropy? Are appropriate timeouts set? Is the Session ID regenerated after login?
Cryptography UsageUse known secure algorithms (AES-256, RSA-2048+); store keys securely; avoid implementing custom encryption
Error HandlingDo error messages avoid leaking internal information (stack traces, SQL statements)? Is there a unified exception handling mechanism?
LoggingAre security events logged? Does logging avoid recording sensitive data (passwords, credit card numbers)?
Third-party PackagesCheck for known vulnerabilities (CVE); lock versions to avoid supply chain attacks

Differences Between DevOps and DevSecOps

  • DevOps focuses on collaboration and automation between development and operations, aiming to accelerate delivery.
  • DevSecOps embeds security controls into every stage of DevOps, aiming for "Security as Guardrails" rather than a gate.
  • Key difference: A DevOps pipeline might only be Build → Test → Deploy; a DevSecOps pipeline is Build → SAST → SCA → Test → DAST → Deploy → Monitor, where security testing is automated and does not block the delivery flow (unless high-risk vulnerabilities are found).

Web Session Management Security

HTTP is a stateless protocol; the server cannot automatically identify if consecutive requests come from the same user. The Session mechanism solves this: after a user is authenticated, the server generates a random Session ID. Subsequent requests include this ID, allowing the server to restore the user's state.

Session ID Transmission Methods:

MethodDescriptionSecurity
Cookie (Recommended)Set-Cookie: sid=xxxx; HttpOnly; Secure; SameSite=LaxHigh (can use attributes to prevent XSS reading and CSRF)
URL Parameter?session=xxxx appended to the URLLow (appears in Server Logs, Referer Headers, browser history; prone to leakage)
Hidden Form Field<input type="hidden" value="xxxx">Low (limited to form submissions; unsuitable for modern apps)

Session State Storage Location (Server-side):

LocationDescriptionUse Case
In-MemoryFastest, but sessions are lost on app restart; cannot share across nodesSingle-node, development environments
DatabasePersistent, but requires DB queries for every request; lower performanceSmall-to-medium apps requiring persistence
Distributed Cache (Redis)Fast and supports multi-node sharing; supports TTL for automatic expirationMainstream choice for modern multi-node web apps
Stateless (JWT)State is stored in the token itself; server does not need to store it; difficult to revokeAPIs / Microservices architecture

Common Attacks and Defenses:

Attack MethodDescriptionCountermeasures
Session HijackingAttacker steals the user's Session ID (e.g., via XSS or network sniffing) to impersonate an authenticated userSet Cookie HttpOnly (prevents XSS reading), Secure (HTTPS only), SameSite=Lax/Strict (prevents CSRF).
Session FixationAttacker pre-sets a known Session ID for the victim; after the victim logs in, the session becomes authenticated, and the attacker uses this ID to accessForce Session Regeneration after successful login.
Session ReplayAttacker intercepts and resends a legitimate Session TokenUse short-lived tokens, bind to Client IP / User-Agent, implement Token Rotation.

Session Management Best Practices

  • Session IDs must be generated by a cryptographically secure random number generator (CSPRNG) and be at least 128 bits long.
  • Set reasonable session timeouts (Idle Timeout and Absolute Timeout).
  • When a user logs out, the server must destroy the session (do not just clear the cookie).
  • In stateless architectures (e.g., JWT), use a short-lived Token + Refresh Token mechanism instead of server-side sessions.

SAST / DAST / IAST / SCA Comparison

ItemSASTDASTIASTSCA
Full NameStatic Application Security TestingDynamic Application Security TestingInteractive Application Security TestingSoftware Composition Analysis
Analysis TargetSource code / Compiled codeRunning applicationRunning application (internal Agent)Third-party dependencies
Testing PhaseDevelopment / CITesting / Pre-productionTesting (requires deployment)Development / CI
ProsEarly detection, broad coverage (including unexecuted paths)Close to real attacks, discovers execution environment issuesCombines SAST/DAST pros, pinpoints code line numbersAutomatically compares against vulnerability databases, tracks license compliance; generates SBOM for supply chain management
ConsHigher false positive rate, cannot find runtime issuesCannot pinpoint source code, coverage limited by test casesRequires modifying deployment environment, performance impactCannot find vulnerabilities in custom-written code
Issues FoundSQL Injection, XSS, Buffer Overflow, etc.Runtime vulnerabilities, misconfigurations, auth issuesCombines issues found by SAST and DASTKnown CVE vulnerabilities, license compliance risks
Requires Source✅ Yes❌ No❌ No (but requires Agent deployment)✅ Yes (scans dependency list)
Typical ToolsSonarQube, Checkmarx, Roslyn AnalyzerOWASP ZAP, Burp SuiteContrast Security, SeekerSnyk, Dependabot, OWASP Dependency-Check

Positioning: Shift Left, DevSecOps, and SCA

  • Shift Left Security: Moving security testing earlier into the development cycle (requirements/design phase) to reduce remediation costs.
  • DevSecOps: Automating security testing within the DevOps CI/CD pipeline (e.g., integrating SAST/DAST/SCA scans) to make security part of continuous delivery.
  • SCA: Scans third-party dependencies for known vulnerabilities and can generate an SBOM (Software Bill of Materials), listing all project dependencies and versions for compliance auditing and supply chain management.

Common Security Testing and Scanning Tools

Static Analysis (SAST) Tools

ToolDescription
SonarQubeOpen-source platform for code quality and security scanning, supports 30+ languages
CheckmarxCommercial enterprise-grade SAST tool, supports multi-language and CI/CD integration
Fortify (Micro Focus)Commercial static analysis tool with an extensive vulnerability rule library
SemgrepOpen-source rule-based scanning tool for matching code patterns
CodeQL (GitHub)GitHub's built-in semantic analysis engine; allows writing queries to find vulnerabilities
Roslyn Analyzer.NET-specific compile-time static analysis, integrated into Visual Studio and CI

Dynamic Analysis (DAST) Tools

ToolDescription
ZAP by CheckmarxOpen-source web app security scanner, supports active scanning and intercepting proxies
Burp Suite (PortSwigger)Industry-standard web security testing platform, available in Community and Professional editions
AcunetixCommercial web vulnerability scanner, supports automated crawling and scanning
NiktoOpen-source web server scanner for detecting known server configuration issues

Penetration Testing Tools

ToolDescription
Metasploit Framework (Rapid7)Open-source/commercial penetration testing framework with built-in exploit modules
NmapNetwork scanning and service discovery tool for host discovery and port scanning
WiresharkOpen-source packet analysis tool for capturing and parsing network traffic
John the Ripper / HashcatPassword cracking tools supporting dictionary and brute-force attacks
Aircrack-ngWireless network security assessment suite for Wi-Fi encryption analysis
sqlmapOpen-source tool for automated SQL Injection detection and exploitation
Cobalt StrikeCommercial red teaming platform for simulating APT attack chains

Vulnerability Scanning Tools

ToolDescription
Nessus (Tenable)Commercial vulnerability scanner covering OS, network devices, and applications
OpenVASOpen-source vulnerability scanner maintained by Greenbone
QualysCloud-based SaaS vulnerability management platform providing continuous scanning and compliance reports

Stress / Load Testing Tools

ToolDescription
Apache JMeterOpen-source load testing tool supporting HTTP, JDBC, and other protocols
LocustPython-based open-source load testing framework; defines test scenarios in code
k6 (Grafana Labs)Open-source performance testing tool using JavaScript for test scripts
LOIC / HOICDDoS attack tools (⚠️ For educational purposes in authorized environments only; unauthorized use is illegal)

Fuzzing

Fuzzing involves automatically generating large amounts of random, malformed, or boundary-value input data and sending it to a target program to observe crashes, memory leaks, or unexpected behavior.

TypeDescription
Dumb Fuzzing (Black-box)Generates completely random input without knowledge of the target format; low coverage but simple to implement
Smart Fuzzing (White/Grey-box)Generates structured, mutated input based on format specifications (e.g., Protocol Buffer, JSON Schema); high coverage
Coverage-guided FuzzingMonitors code coverage and prioritizes mutations that reach new paths (e.g., AFL, libFuzzer)
  • Fuzzing is effective at discovering memory safety issues like buffer overflows, format string vulnerabilities, and integer overflows.
  • Google OSS-Fuzz continuously performs fuzzing on open-source projects and has discovered over 10,000 vulnerabilities.

CI/CD Pipeline Security

Security AspectDescription
Pipeline as CodeStore pipeline definitions in version control (e.g., .gitlab-ci.yml, Jenkinsfile); changes require code review to prevent unauthorized build process modifications
Secret ManagementPasswords and API keys in CI/CD must not be hardcoded; use CI platform secret management (e.g., GitHub Actions Secrets, Azure Key Vault)
Secret ScanningScan codebases for accidentally committed secrets (API keys, passwords, private keys) using tools like gitleaks, truffleHog, or GitHub Secret Scanning
Dependency ScanningAutomatically scan third-party package vulnerabilities (SCA) and integrate into the pipeline to run on every build
Artifact SigningDigitally sign build artifacts (Container Images, NuGet Packages) to ensure the deployed version is verified
Principle of Least PrivilegeGrant CI/CD Service Accounts only necessary permissions; isolate Runners/Agents from the production environment

DevSecOps Pipeline Workflow

Diagram
Git Secret Scanning Commands
bash
# gitleaks: Scan Git history for secrets
gitleaks detect --source=. --report-format=json --report-path=gitleaks-report.json

# truffleHog: Scan for high-entropy strings and known secret patterns
trufflehog git file://. --json

# Install as a Git pre-commit hook to prevent secret commits
# .pre-commit-config.yaml example:
# repos:
#   - repo: https://github.com/gitleaks/gitleaks
#     rev: v8.18.0
#     hooks:
#       - id: gitleaks
C# Example: Custom Roslyn Analyzer (Detecting Hardcoded Connection Strings)

Roslyn Analyzer is a .NET SAST tool that detects security issues in real-time during compilation. The following demonstrates a custom rule for detecting hardcoded connection strings:

csharp
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class HardcodedConnectionStringAnalyzer : DiagnosticAnalyzer {
    private static readonly DiagnosticDescriptor Rule = new(
        id: "SEC001",
        title: "Hardcoded Connection String Detected",
        messageFormat: "Connection strings should not be hardcoded in source code; use environment variables or a Secret Manager instead",
        category: "Security",
        defaultSeverity: DiagnosticSeverity.Warning,
        isEnabledByDefault: true
    );

    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
        ImmutableArray.Create(Rule);

    public override void Initialize(AnalysisContext context) {
        context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
        context.EnableConcurrentExecution();
        context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.StringLiteralExpression);
    }

    private static void AnalyzeNode(SyntaxNodeAnalysisContext context) {
        LiteralExpressionSyntax literal = (LiteralExpressionSyntax)context.Node;
        string value = literal.Token.ValueText;

        // Detect common connection string patterns
        if (value.Contains("Server=", StringComparison.OrdinalIgnoreCase)
            || value.Contains("Data Source=", StringComparison.OrdinalIgnoreCase)
            || value.Contains("Password=", StringComparison.OrdinalIgnoreCase)
        ) {
            Diagnostic diagnostic = Diagnostic.Create(Rule, literal.GetLocation());
            context.ReportDiagnostic(diagnostic);
        }
    }
}
C# Example: Secure Configuration (Protecting Sensitive appsettings Information)
csharp
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

// ❌ Incorrect: Storing sensitive information directly in appsettings.json
// "ConnectionStrings": { "Default": "Server=prod;Password=P@ssw0rd" }

// ✅ Correct: Use User Secrets (development) or environment variables (production)
// Development: dotnet user-secrets set "ConnectionStrings:Default" "Server=..."
// Production: Inject via environment variable ConnectionStrings__Default

// Enable User Secrets (automatically loaded in Development environment)
if (builder.Environment.IsDevelopment()) {
    builder.Configuration.AddUserSecrets<Program>();
}

// Azure environment: Integrate Azure Key Vault
// builder.Configuration.AddAzureKeyVault(
//     new Uri($"https://{vaultName}.vault.azure.net/"),
//     new DefaultAzureCredential()
// );

// Bind configuration using Options Pattern to avoid scattered GetValue calls
builder.Services.Configure<DatabaseOptions>(
    builder.Configuration.GetSection("Database")
);

WebApplication app = builder.Build();
app.Run();

public class DatabaseOptions {
    public string ConnectionString { get; init; } = "";
    public int CommandTimeout { get; init; } = 30;
}
C# Example: Health Check Endpoint Secure Implementation
csharp
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using System.Text.Json;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Services.AddHealthChecks()
    .AddCheck("self", () => HealthCheckResult.Healthy(), tags: ["live"])
    .AddCheck<DatabaseHealthCheck>("database", tags: ["ready"]);

WebApplication app = builder.Build();

// Liveness: Verify if the application itself is alive (used by Kubernetes livenessProbe)
app.MapHealthChecks("/healthz/live", new HealthCheckOptions {
    Predicate = check => check.Tags.Contains("live"),
    // Security: Do not expose detailed information externally
    ResponseWriter = async (context, report) => {
        context.Response.ContentType = "application/json";
        await context.Response.WriteAsync(
            JsonSerializer.Serialize(new { status = report.Status.ToString() })
        );
    }
});

// Readiness: Verify if the application and its dependencies are ready (used by Kubernetes readinessProbe)
app.MapHealthChecks("/healthz/ready", new HealthCheckOptions {
    Predicate = check => check.Tags.Contains("ready"),
    ResponseWriter = async (context, report) => {
        context.Response.ContentType = "application/json";
        await context.Response.WriteAsync(
            JsonSerializer.Serialize(new { status = report.Status.ToString() })
        );
    }
});

// Security measure: Health Check Endpoint should not be exposed to the public internet
// Method 1: Restrict IP range
// Method 2: Require authentication (though Kubernetes Probes often cannot carry tokens)
// Method 3: Bind Health Endpoint to a different port (Management Port)
// builder.WebHost.UseUrls("http://*:8080", "http://*:9090");
// app.MapHealthChecks("/healthz/live").RequireHost("*:9090");

app.Run();

public class DatabaseHealthCheck : IHealthCheck {
    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context,
        CancellationToken cancellationToken = default
    ) {
        try {
            // Actual database connection check
            // await dbContext.Database.CanConnectAsync(cancellationToken);
            return HealthCheckResult.Healthy("Database connection OK");
        } catch (Exception ex) {
            // Security: Do not expose exception details in the response; log them instead
            return HealthCheckResult.Unhealthy(
                "Database unavailable",
                exception: ex
            );
        }
    }
}

SBOM (Software Bill of Materials)

An SBOM is a list of software components that records all dependencies, version numbers, and licensing information included in an application, similar to a "bill of materials" in the manufacturing industry.

Standard FormatMaintaining OrganizationFeatures
SPDXLinux FoundationFocuses on license compliance; ISO/IEC 5962 international standard
CycloneDXOWASPFocuses on security analysis; supports vulnerability tracking and service components (SaaSBOM)

Practical Uses of SBOM

  • Uses:
    • Supply Chain Security: Quickly confirm whether packages affected by vulnerabilities are being used (e.g., in the Log4Shell incident, organizations with an SBOM could complete impact assessments within hours).
    • Vulnerability Tracking: Automatically cross-reference with CVE databases to identify known vulnerabilities.
    • Compliance Auditing: Meet license compliance requirements (e.g., identifying copyleft licenses like GPL).
  • The U.S. 2021 Executive Order (EO 14028) requires federal government suppliers to provide an SBOM.
  • SBOMs should be integrated into the build phase of SSDLC and automatically generated within the CI/CD pipeline.

VEX (Vulnerability Exploitability eXchange) is a companion standard to SBOM that uses a machine-readable format to declare whether a specific CVE actually affects a particular product version.

VEX StatusMeaning
Not AffectedThis CVE does not affect the product (e.g., the vulnerable code path is never called, or the platform is different)
AffectedConfirmed to be affected; should be patched as soon as possible
FixedAlready fixed in the specified version
Under InvestigationCurrently being evaluated; no conclusion yet

VEX Complements SBOM Limitations

  • Problems Solved by VEX: An SBOM can only list "which packages are used," but it cannot explain "whether this vulnerability actually poses a threat to me." VEX fills this information gap, allowing security teams to prioritize vulnerabilities that have a real impact rather than treating every CVE equally.
  • Publisher: Product vendors or developers, not the CVE database.
  • Format: Both CycloneDX and CSAF (Common Security Advisory Framework) support the VEX format.
  • The U.S. CISA recommends using SBOM and VEX together as a complete solution for software supply chain transparency.

SBOM Format Comparison: CycloneDX vs SPDX

AspectCycloneDXSPDX
Maintaining OrganizationOWASPLinux Foundation
Design GoalSecurity analysis and vulnerability trackingLicense compliance and IP management
International StandardECMA-424ISO/IEC 5962
VEX SupportNative/Built-inRequires CSAF format
SaaSBOM Support✅ Supported (Service component list)❌ Not supported
FormatJSON, XML, Protocol BuffersJSON, RDF, Tag-Value, XLSX
Tool Ecosystemsyft, cdxgen, CycloneDX CLISPDX tools, FOSSology
  • If your requirements focus on security vulnerability management, choose CycloneDX.
  • If your requirements focus on license compliance or require ISO standard compliance, choose SPDX.
  • Both formats can be converted to each other; in practice, the choice depends on the organization's toolchain and compliance needs.
SBOM Generation and Vulnerability Scanning Commands
bash
# syft: Generate SBOM (supports CycloneDX and SPDX formats)
syft myapp:latest -o cyclonedx-json > sbom.cdx.json
syft myapp:latest -o spdx-json > sbom.spdx.json

# cdxgen: Multi-language SBOM generation tool (supports .NET, Node.js, Java, etc.)
cdxgen -o sbom.json --type dotnet

# grype: Vulnerability scanning using SBOM
grype sbom:sbom.cdx.json

# .NET project native SBOM generation (requires Microsoft.Sbom.Tool)
dotnet tool install --global Microsoft.Sbom.Tool
sbom-tool generate -b ./output -bc . -pn MyApp -pv 1.0.0 -ps MyOrg

Container Security

Security AspectDescription
Image ScanningScan container images for known vulnerabilities and malware; intercept risky images during the CI/CD phase. Tools: Trivy, Grype, Snyk Container
Base Image ManagementUse official or verified minimal images (e.g., alpine, distroless) to reduce the attack surface
Runtime ProtectionMonitor container behavior at runtime to detect anomalies (e.g., unexpected network connections, file system changes). Tools: Falco, Sysdig
Pod Security (Kubernetes)Kubernetes Pod Security Standards define three levels: Privileged (unrestricted), Baseline (prevents known privilege escalation), Restricted (most strict)
Immutable ContainerSet the container file system to read-only (readOnlyRootFilesystem: true); modifications are not allowed at runtime, reducing the risk of backdoor injection
Registry SecurityEnable access control and image signature verification (e.g., Cosign / Notary) on private registries to prevent pulling tampered images

Container vs. VM Security Differences

  • Containers share the Host OS Kernel, making isolation weaker than VMs (Hypervisor isolation). Container Escape can lead to direct access to the Host.
  • Compensating Controls: Use seccomp profiles to restrict system calls, AppArmor/SELinux for mandatory access control, and run containers as non-root users.
  • Kubernetes NetworkPolicy can restrict network communication between Pods (by default, Pods can communicate freely).
Docker Security Scanning Commands
bash
# Trivy: Container image vulnerability scanning (shows only HIGH and CRITICAL)
trivy image --severity HIGH,CRITICAL myapp:latest

# Grype: Another image scanning tool (shows only vulnerabilities with fixed versions)
grype myapp:latest --only-fixed

# Docker Scout (Built-in to Docker)
docker scout cves myapp:latest

# Trivy scanning for Kubernetes cluster configuration
trivy k8s --report summary cluster

Infrastructure as Code Security

IaC defines infrastructure as version-controlled code files, but misconfigurations can lead to security vulnerabilities (e.g., public S3 buckets, overly permissive firewall rules).

Inspection AspectDescription
Static AnalysisScan IaC templates for security misconfigurations before deployment. Tools: Checkov (multi-framework support), KICS, Trivy (includes IaC scanning)
Policy as CodeDefine compliance policies as code (e.g., OPA/Rego, Sentinel) and automatically verify them in CI/CD
Drift DetectionDetect discrepancies between the actual environment and IaC definitions to prevent manual changes from bypassing version control
Secrets SeparationIaC templates must not contain passwords or keys; they should reference a Secret Manager or Key Vault
Terraform / IaC Security Scanning Commands
bash
# Checkov: Multi-framework IaC security scanning (Terraform, ARM, CloudFormation, Kubernetes)
checkov -d . --framework terraform

# Checkov scanning for Kubernetes manifests
checkov -d ./k8s/ --framework kubernetes

# tflint: Terraform Linter (includes security rules)
tflint --init && tflint .

GitOps Security

GitOps uses a Git repository as the single source of truth for infrastructure and application deployment, controlling deployments through Git change processes (PR / Merge Request).

Security FeatureDescription
Change AuditingAll deployment changes have Git commit records, providing a complete audit trail
Pull-based DeploymentDeployment agents (e.g., ArgoCD, Flux) pull configurations from Git, eliminating the need to expose Cluster credentials to CI systems
Automatic RollbackAutomatically synchronizes back to the state defined in Git when environment drift occurs, ensuring declarative consistency

GitOps Security Considerations

  • The Git repository itself becomes an attack target: enable branch protection rules, enforce code reviews, and require MFA.
  • Secrets should not be stored in Git in plaintext: use Sealed Secrets, SOPS, or external Secret Managers to encrypt them before storage.

DevSecOps Tools Comparison Table (Linux / macOS / Windows)

DomainLinux / macOSWindows / AzureDescription
Container EngineDocker Engine, PodmanDocker Desktop, Windows ContainerPodman is a daemonless architecture; Windows Container supports Process and Hyper-V isolation modes
CI/CDJenkins, GitLab CI, GitHub ActionsAzure DevOps Pipelines, GitHub ActionsGitHub Actions is cross-platform; Azure DevOps integrates with the Azure ecosystem
Logging & MonitoringELK Stack (Elasticsearch + Logstash + Kibana), Prometheus + GrafanaAzure Monitor, Splunk, Application InsightsELK is an open-source solution; Splunk and Azure Monitor are commercial solutions providing advanced analytics and alerting
IaCTerraform, Ansible, PulumiARM Template, Bicep, PowerShell DSCTerraform is a cross-cloud solution; Bicep is syntactic sugar for ARM Templates, applicable only to Azure; PowerShell DSC is for Windows server configuration management
Secret ManagementHashiCorp VaultAzure Key Vault, AWS Secrets ManagerVault is a cross-platform solution; cloud Key Vaults are deeply integrated with cloud IAM

Deployment Strategy Comparison Table

StrategyMechanism DescriptionRisk LevelRollback SpeedApplicable Scenarios
Blue-GreenMaintain two complete environments (Blue/Green); deploy the new version to the inactive environment and switch traffic after testing.LowVery Fast (switch back to old environment)Critical services requiring zero downtime and high rollback requirements
CanaryPush the new version to a small percentage of users (e.g., 5%) first, observe metrics, and gradually expand; roll back immediately if anomalies occur.Low to MediumFast (scale back percentage)Large-scale services, scenarios requiring progressive validation
RollingReplace instances in batches (e.g., 25% per update) until completion.MediumMedium (requires batch-by-batch rollback)Default strategy for containerized / Kubernetes environments
A/B TestingAssign different versions to different user groups to compare metrics (conversion rate, performance).LowFast (switch groups)Product feature experimentation, UX optimization
Feature FlagControl feature enablement/disablement via configuration; decouple deployment from release; toggle without redeployment.LowVery Fast (turn off flag)Continuous deployment, scenarios requiring dynamic control of feature visibility

Common Deployment Strategy Trade-offs

  • Blue-Green has the highest cost (requires double the infrastructure) but is the safest for rollbacks.
  • Canary is the most common progressive strategy in the industry (widely adopted by Google, Netflix). Named after the "canary in a coal mine": test with a small number of users first to detect issues early.
  • Rolling is the default update strategy for Kubernetes Deployments (strategy.type: RollingUpdate).
  • Feature Flag is not a deployment strategy itself but an auxiliary mechanism that can be used with any deployment strategy.
  • The choice of Deployment Strategy depends on service scale, infrastructure costs, and acceptable risk levels.

Chaos Engineering

Chaos Engineering verifies system resilience and fault tolerance in a controlled environment by proactively injecting failures (e.g., randomly terminating service instances, simulating network latency). From a security perspective, it can also be used to test whether security controls remain effective under abnormal conditions, such as whether a WAF continues to filter attacks under high traffic impact.

AspectChaos EngineeringPenetration TestingDR Drill (Full Outage Test)
PurposeVerify if the system can recover automatically from failuresIdentify exploitable security vulnerabilitiesVerify failover capabilities and RTO/RPO
Test ObjectTechnical systems (automation layer)Attack surface and vulnerabilitiesTechnical systems + recovery processes
EnvironmentProduction (controlled)Primarily test environmentUsually in test environment
Fault SourceEngineers proactively inject technical faultsSimulate attacker techniquesSimulate major disaster scenarios
FrequencyContinuous or high frequencyPeriodic (annual / quarterly)Periodic (annual)
ConceptDescription
Steady State HypothesisDefine measurable metrics for normal system operation (e.g., response time < 200ms, error rate < 0.1%) as a baseline for experiments
Blast RadiusLimit the scope of experimental impact, starting small (e.g., a single Pod) and expanding gradually
Game DayTeams regularly simulate real-world failure scenarios (e.g., regional power outage) to practice incident response processes

Chaos Engineering Implementation Principles

  • Netflix's Chaos Monkey is the most well-known chaos engineering tool, randomly terminating VM instances in production.
  • Chaos engineering is not random destruction, but a scientific experiment that is hypothesized, measured, and controlled.

Change Log

  • 2026-05-02 Initial document creation.
  • 2026-05-21
    • Added understanding-aid charts for each chapter (Mermaid and ECB pattern penguin visual comparison).
    • Corrected terminology and standardized on Taiwan-specific usage.
    • Added technical details (new MTTP patching metrics, analogies, and transition phrases).
    • Consolidated redundant linear diagrams for Cyber Kill Chain.
  • 2026-05-23
    • Rewrote the asset classification and grading chapter, filling in the context for asset inventory, sensitivity, and criticality assessment.
    • Updated OWASP Top 10 to the 2025 version and added the OWASP Cloud-Native Application Security (CNAS) Top 10 checklist.
    • Added content on regulations, compliance, and audit frameworks, and corrected descriptions related to GDPR, Taiwan's Personal Data Protection Act, and the Cyber Security Management Act.
    • Adjusted descriptions of recent specifications like TLS, OAuth, and FIDO2 / Passkey, converging on less absolute statements.
    • Expanded the organizational context for identity access, SOC, cloud security, and DevSecOps chapters.
    • Adjusted the IaC security scanning tool list, removing tfsec-related content.